Home / C Sharp / Archive by category 'C# XML'

C# XML

Delete a specific xml node in xml file using C#

protected void DeleteXmlNode(int selectedIndex)
{
    XmlDocument docXml = new XmlDocument();
    docXml.Load(Server.MapPath(@"App_Data\myXmlFile.xml")); //locate and load xml file in application
    XmlNode node = docXml.DocumentElement.ChildNodes.Item(selectedIndex); //locate specific index node
    node.ParentNode.RemoveChild(node); //remove node
    docXml.Save(Server.MapPath(@"App_Data\mynewXmlFile.xml")); //save file
}

Write to an Xml file using Xml Writer in C#

C# provides the XmlWriter class which allows developers to write to an Xml file. To begin, we need to import the system.xml namespace.

using System.Xml;

The system.xml namespace contains the XmlWriter and XmlTextWriter classes.

To read an xml file to write out, we can call the constructor of the XmlTextWriter class. This will read the xml file specified, so that it can be manipulated.

XmlTextWriter xmlWriter = new XmlTextWriter("C:\\Temp\myTestXml.xml", null);

This would create the file C:\\Temp\myTestXml.xml if it did’nt exist.

We can write a comment into the xml file using

xmlWriter.WriteComment("This is a comment in the xml file");
xmlWriter.Flush()

To write out/display the xml content in the file in a shot, we can pass Console.Out as a parameter of the constructor to the XmlTextWriter.

XmlTextWriter writer = new XmlTextWriter(Console.Out);

Add custom data to xml node and save xml file in C#

protected void AddNodeToXml()
    {
        XmlDocument docXml = new XmlDocument();
        docXml.Load(Server.MapPath(@"App_Data\myXmlFile.xml")); //locate the xml file
 
        //Create the node to set the data
        XmlElement element = docXml.CreateElement("userprofile");
        XmlElement xmlUser = docXml.CreateElement("User");
        XmlElement xmlPass = docXml.CreateElement("Password");
 
        xmlUser.InnerText = this.txtUser.Text.Trim();
        xmlPass.InnerText = this.txtPass.Text.Trim();
 
        element.AppendChild(xmlUser);
        element.AppendChild(xmlPass);
 
        docXml.DocumentElement.AppendChild(element);
        docXml.Save(Server.MapPath(@"App_Data\myXmlFile.xml")); //save the xml file
   }

Find a specific node in XML using XmlDocument, XmlNodeList and XmlNode in C#

private void FindXmlDataItem(int sIndex)
{
    XmlDocument docXml = new XmlDocument();
    docXml.Load(Server.MapPath(@"App_Data\myXmlFile.xml"));
    XmlNodeList list = docXml.DocumentElement.ChildNodes;
    XmlNode node = list.Item(sIndex);
    this.txtUser.Text = node["User"].InnerText;
    this.txtPass.Text = node["Password"].InnerText;
}

Load xml file to xml dataset and bind to gridview in C#

In the method shown below, we will locate xml file within application, read it to a dataset and then set the xml dataset as datasource to grid view.

private void loadandbindXmlData()
{
    DataSet xmlData = new DataSet();
    xmlData.ReadXml(Server.MapPath(@"App_Data\myXmlFile.xml")); //locate xml file within application
    if (xmlData.Tables.Count > 0)
    {
        GVXmlData.DataSource = xmlData; //set xml dataset as datasource to grid view.
        GVXmlData.DataBind();
    }
}

Which of the following are requirements for a class to be serialized with XML serialization?

Which of the following are requirements for a class to be serialized with XML serialization?
A. The class must be public.
B. The class must be private.
C. The class must have a parameterless constructor.
D. The class must have a constructor that accepts a SerializationInfo parameter.

Classes serialized with XML serialization must be public. For XML serialization to work, the class must have a parameterless constructor.


Which of the following attributes would you use to cause a member to be serialized as an XML attribute, rather than as an XML element?

Which of the following attributes would you use to cause a member to be serialized as an XML attribute, rather than as an XML element?
A. XmlAnyAttribute
B. XmlType
C. XmlElement
D. XmlAttribute

Add the XMLAttribute attribute to serialize a member as an attribute.


Which tool would you use to help you create a class that, when serialized, would produce an XML document that conformed to an XML schema?

Which tool would you use to help you create a class that, when serialized, would produce an XML document that conformed to an XML schema?
A. Xsd.exe
B. Xdcmake.exe
C. XPadsi90.exe
D. Xcacls.exe

You can use the Xsd.exe tool to create classes based on an XML schema.


Which of the following attributes should you add to a member to prevent it from being serialized by XML serialization?

Which of the following attributes should you add to a member to prevent it from being serialized by XML serialization?
A. XmlType
B. XmlIgnore
C. XmlElement
D. XmlAttribute

Use the XMLIgnore attribute to prevent a member from being serialized during XML serialization.


Creating attributes while serializing object to xml in C#

We can use the XmlAttribute annotation for a public field, property or parameter for the member to be serialized as an XML attribute. The XmlIgnore annotation can be applied to public fields or properties to make the xmlserializer ignore the field while serialization.

[XmlRoot ("CartItem")]
public class ShoppingCartItem
{
[XmlAttribute] public Int32 productId;
public decimal price;
public Int32 quantity;
[XmlIgnore] public decimal total;
public ShoppingCartItem()
{
}
}

Output xml:

<?xml version="1.0" ?>
<CartItem productId="100">
<price>10.25</price>
<quantity>2</quantity>
</CartItem>

How to Use XML to Deserialize an Object in C#

1. Create a stream, TextReader, or XmlReader object to read the serialized input.
2. Create an XmlSerializer object (in the System.Xml.Serialization namespace) by passing it the type of object you plan to deserialize.
3. Call the XmlSerializer.Deserialize method to deserialize the object, and cast it to the correct type.

Example:

// Open file from which to read the data
FileStream fs = new FileStream("SerializedDate.XML", FileMode.Open);
 
// Create an XmlSerializer object to perform the deserialization
XmlSerializer xs = new XmlSerializer(typeof(DateTime));
 
// Use the XmlSerializer object to deserialize the data from the file
DateTime previousTime = (DateTime)xs.Deserialize(fs);
 
// Close the file
fs.Close();
 
// Display the deserialized time
Console.WriteLine("Day: " + previousTime.DayOfWeek + ", Time: " + previousTime.TimeOfDay.ToString());

How to Use XML to Serialize an Object in C#

1. Create a stream, TextWriter, or XmlWriter object to hold the serialized output.
2. Create an XmlSerializer object (in the System.Xml.Serialization namespace) by passing it the type of object you plan to serialize.
3. Call the XmlSerializer.Serialize method to serialize the object and output the results to the stream.

Example:

// Create file to save the data
FileStream fs = new FileStream("SerializedDate.XML", FileMode.Create);
 
// Create an XmlSerializer object to perform the serialization
XmlSerializer xs = new XmlSerializer(typeof(DateTime));
 
// Use the XmlSerializer object to serialize the datetime data to the file
xs.Serialize(fs, System.DateTime.Now);
 
// Close the file
fs.Close();

Output in the xml file:

<?xml version="1.0" ?>
<dateTime>2010-05-05T16:28:11.0533408-05:00</dateTime>

Limitations of XML serialization

XML serialization has the following limitations
1. XML serialization can serialize only public data. You cannot serialize private data.
2. You cannot serialize object graphs; you can use XML serialization only on objects


What is XPath?

XPath is one of the possible ways to query data in XML documents. To use XPath, you must be familiar with the structure of the XML document in order to be able to select individual elements from it. Though XPath can be used on any well-formed XML document, the fact that you must know the structure of the document when you create the query means that ensuring that the document is valid also ensures that the query will work from document to document, as long as the documents are valid against the same schema.


What is an XML schema?

XML schema is used to define the structure of XML documents. Schemas are especially useful when you need to exchange information with third parties. By agreeing on a schema for the data that is exchanged, you and the third party will be able to check that the documents are valid.


What is a Valid XML?

Valid XML is XML that is well-formed and can be validated by checking that it can be generated from a schema. Ensuring that XML is valid is important because it lets you make assumptions about the content of the XML document, which allows you to work with documents that were generated by others with the knowledge that the structure and names within the document are exactly as expected.


What is a Well-formed XML?

Well-formed XML is XML that adheres to the basic syntax rules of XML. A document is said to be well-formed when there is precisely one root element, and every element has a closing tag, no elements overlap other elements (all child elements must be fully nested within the parent), and all attributes enclosed in quotes. All XML readers can read well-formed XML – but very few if any will allow you to read documents that are not well-formed. Strictly speaking, if a document containing tags isn’t well-formed then it is not an XML document.


Common XPath Operations

.
Select the current node.

..
Select the parent of the current node.

*
Select all child nodes of the current node.

title
Select all child nodes with a specific name — in this case, title.

@Type
Select an attribute of the current node.

@*
Select all attributes of the current node.

element[2]
Select a child node by index — in this case, the second element node.

text()
Select all the text nodes of the current node.

element/text()
Select one or more grandchildren of the current node.

//items
Select all nodes in the document with a particular name — in this case, all items nodes.

//element/name
Select all nodes in the document with a particular name and a particular parent name — in this case, the parent name is element and the node name is name.

//element[name=’Hydrogen’]
Select a node where a value criterion is met — in this case, the element for which the name of the element is Hydrogen.

//element[@Type=’Noble Gas’]
Select a node where an attribute value criterion is met — in this case, the Type attribute = Noble Gas.


Deleting Nodes from a XMLDocument using c# .NET

After the initial steps to load the XML into the XmlDocument object, you examine the root element to see whether there are any child elements in the XML you loaded. If there are, then you use the LastChild property of the XmlElement class to get the last child. After that, removing the element is as simple as calling RemoveChild, passing in the instance of the element you wish to remove.

Input Xml:

<?xml version="1.0"?>
<books>
  <book>
    <title>This is title1</title>
    <author>author1</author>
    <code>1234</code>
  </book>
  <book>
    <title>This is title2</title>
    <author>author2</author>
    <code>4352</code>
  </book>
</books>

Example:

  private void buttonDeleteNode_Click(object sender, EventArgs e)
    {
      // Load the XML document.
      XmlDocument document = new XmlDocument();
      document.Load("Books.xml");
 
      // Get the root element.
      XmlElement root = document.DocumentElement;
 
      // Find the node. root is the <books> tag, so its last child
      // which will be the last <book> node.
      if (root.HasChildNodes)
      {
        XmlNode book = root.LastChild;
 
        // Delete the child.
        root.RemoveChild(book);
 
        // Save the document back to disk.
        document.Save("Books.xml");
      }
 
    }

Creating Nodes in an XMLDocument using c# .NET

The XmlDocument class has methods that enable you to create new XmlNode and XmlElement instances.

<?xml version="1.0"?>
<books>
  <book>
    <title>This is title1</title>
    <author>author1</author>
    <code>1234</code>
  </book>
  <book>
    <title>This is title2</title>
    <author>author2</author>
    <code>4352</code>
  </book>
</books>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
 
namespace LoopThroughXmlDocument
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }
 
    private void buttonLoopThroughDocument_Click(object sender, EventArgs e)
    {
      XmlDocument document = new XmlDocument();
 
      // A Post event (on the properties page for the project) copies the XML to the
      // output folder whenever you compile, which is why no explicit path is needed.
      document.Load(@"Books.xml");
      textBoxResult.Text = FormatText(document.DocumentElement as XmlNode, "", "");
    }
 
    private string FormatText(XmlNode node, string text, string indent)
    {
      if (node is XmlText)
      {
        text += node.Value;
        return text;
      }
 
      if (string.IsNullOrEmpty(indent))
        indent = "";
      else
      {
        text += "\r\n" + indent;
      }
 
      if (node is XmlComment)
      {
        text += node.OuterXml;
        return text;
      }
 
      text += "<" + node.Name;
      if (node.Attributes.Count > 0)
      {
        AddAttributes(node, ref text);
      }
      if (node.HasChildNodes)
      {
        text += ">";
        foreach (XmlNode child in node.ChildNodes)
        {
          text = FormatText(child, text, indent + "  ");
        }
        if (node.ChildNodes.Count == 1 &&
           (node.FirstChild is XmlText || node.FirstChild is XmlComment))
          text += "</" + node.Name + ">";
        else
          text += "\r\n" + indent + "</" + node.Name + ">";
      }
      else
        text += " />";
      return text;
    }
 
    private void AddAttributes(XmlNode node, ref string text)
    {
      foreach (XmlAttribute xa in node.Attributes)
      {
        text += " " + xa.Name + "='" + xa.Value + "'";
      }
    }
 
    private void buttonCreateNode_Click(object sender, EventArgs e)
    {
      // Load the XML document.
      XmlDocument document = new XmlDocument();
      document.Load(@"Books.xml");
 
      // Get the root element.
      XmlElement root = document.DocumentElement;
 
      // Create the new nodes.
      XmlElement newBook = document.CreateElement("book");
      XmlElement newTitle = document.CreateElement("title");
      XmlElement newAuthor = document.CreateElement("author");
      XmlElement newCode = document.CreateElement("code");
      XmlText title = document.CreateTextNode("this is title3");
      XmlText author = document.CreateTextNode("author3");
      XmlText code = document.CreateTextNode("12390");
      XmlComment comment = document.CreateComment("This book is the book you are reading");
 
      // Insert the elements.
      newBook.AppendChild(comment);
      newBook.AppendChild(newTitle);
      newBook.AppendChild(newAuthor);
      newBook.AppendChild(newCode);
      newTitle.AppendChild(title);
      newAuthor.AppendChild(author);
      newCode.AppendChild(code);
      root.InsertAfter(newBook, root.FirstChild);
 
      document.Save(@"Books.xml");
 
    }
  }
}