12 October 2011

XML File Reading & Writing - Simplified

Simple Example of Reading & Writing a xml file

Sample XML File:
<?xml version="1.0" encoding="utf-8"?>
<Products>
  <Product>
    <Id>1</Id>
    <Name>Froyo</Name>
    <Cost>10.50</Cost>
  </Product>
  <Product>
    <Id>2</Id>
    <Name>Gingerbread</Name>
    <Cost>20.60</Cost>
  </Product>
  <Product>
    <Id>3</Id>
    <Name>Ice Cream Sandwich</Name>
    <Cost>30.70</Cost>
  </Product>
</Products>

C# code to create such file:

    XmlDocument doc = new XmlDocument();
                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
                doc.AppendChild(dec);// Create the root element
                XmlElement root = doc.CreateElement("Products");
                doc.AppendChild(root);

    //ProductList can be any collection or array etc
                foreach (product p1 in productList)
                {
                    XmlElement product = doc.CreateElement("Product");

                    XmlElement id = doc.CreateElement("Id");
                    id.InnerText = p1._id.ToString();

                    XmlElement name = doc.CreateElement("Name");
                    name.InnerText = p1._name;

                    XmlElement validation = doc.CreateElement("Validation");
                    validation.InnerText = p1._validation.ToString();

                    product.AppendChild(id);
                    product.AppendChild(name);
                    product.AppendChild(validation);

                    root.AppendChild(product);
                }

                string xmlOutput = doc.OuterXml;

C# code to read such a file:

    if (File.Exists(FilePath))
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(FilePath);

                    foreach (XmlNode node in doc.DocumentElement.SelectNodes("Product"))
                    {
                        int pid = Convert.ToInt32(node.SelectSingleNode("Id").InnerText);
                        string pname = node.SelectSingleNode("Name").InnerText;
                        double cost= Convert.ToDouble(node.SelectSingleNode("Cost").InnerText);                       
                    }
                }

Short an simple....something to remember :)