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"?>
    <Name>Ice Cream Sandwich</Name>

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");

    //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();



                string xmlOutput = doc.OuterXml;

C# code to read such a file:

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

                    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 :)

1 comment:

Anonymous said...

Why stopped blogging????