C# create read write XML file

Sample file

<?xml version="1.0" encoding="utf-8"?>
<root>
  <property name="One">One</property>
  <values>
    <value name="Two">Two</value>
    <value name="Three">Three</value>
  </values>
</root>

Creating/Writing XML file

public void TestXMLWriter()
{
  string filePath = @"c:\temp\sample.xml";
  List<string> values = new List<string>();
  values.Add("Two");
  values.Add("Three");
  XmlWriterSettings xmlSettings = new XmlWriterSettings();
  xmlSettings.Indent = true;
  xmlSettings.Encoding = Encoding.UTF8;
  using (XmlWriter writer = XmlWriter.Create(
    filePath,
    xmlSettings
    ))
  {
    writer.WriteStartDocument();
    writer.WriteStartElement("root");
    {
      writer.WriteStartElement("property");
      writer.WriteAttributeString("name", "One");
      writer.WriteString("One");
      writer.WriteEndElement();
      
      writer.WriteStartElement("values");
      {
        foreach (string value in values)
        {
          writer.WriteStartElement("value");
          writer.WriteAttributeString("name", value);                                    
          writer.WriteString(value);
          writer.WriteEndElement();
        }                            
      }
      writer.WriteEndElement();
    }    
    writer.WriteEndElement();
    writer.WriteEndDocument();
  }
}

Reading XML file

public void TestRead()
{
  string filePath = @"c:\temp\sample.xml";
  XPathDocument doc = new XPathDocument(filePath);
  XPathNavigator nav = doc.CreateNavigator();
  XPathNodeIterator nodeIterator = nav.Select("/root");
  foreach (XPathNavigator node in nodeIterator)
  {
    Console.WriteLine("Property Attribute: {0}",node.SelectSingleNode("property").Value);
    Console.WriteLine("Property Value: {0}",node.SelectSingleNode("property").GetAttribute("name",""));
    foreach (XPathNavigator subNode in node.Select("values/value"))
    {
      Console.WriteLine("Value Attribute: {0}", subNode.Value);
      Console.WriteLine("Value Value: {0}", subNode.GetAttribute("name", ""));
    }
  }            
}

Comments

  1. Very nice article. I really enjoyed it reading. And it also cleared lot of my doubts about reading and writing XML in C#.Net, Well done job!
    Check this link too....
    How to read and write XML in C#

    It helped me lot in completing my task.

    Thanks Everyone for precious post!

    ReplyDelete
  2. Thanks for sharing the best information and suggestions, it is very nice and very useful to us. I appreciate the work that you have shared in this post. Keep sharing these types of articles here. Global Online Match Match Finding Website

    ReplyDelete

Post a Comment

Popular posts from this blog

Tibco Rendezvous (tibrv) C# .Net example

Parse XML to dynamic object in C#