Thursday, 29 September 2011

Parse an XML string/file in C#


The following code shows a simple method of parsing through an XML string/file. We can get the parent name, child name, attributes etc. from the XML. The namespace System.Xml would be the only additional namespace that we would be using.
string myXMl = "<Employees>" +
                 "<Employee ID='1' Name='Ravi'" +
                      "Address='Pandav Nagar'" +
                      "City='New Delhi' Zip='110092'>" +
                 "</Employee>" +
               "</Employees>";

XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(myXMl);

XmlNodeList xNodeList = xDoc.SelectNodes("Employees/child::node()");
foreach (XmlNode xNode in xNodeList)
{
  if (xNode.Name == "Employee")
  {
    string ID = xNode.Attributes["ID"].Value; //Outputs: 1
   
string Name = xNode.Attributes["Name"].Value; //Outputs: Ravi
   
string Address = xNode.Attributes["Address"].Value; //Outputs: Pandav Nagar
   
string City = xNode.Attributes["City"].Value; //Outputs: New Delhi
   
string Zip = xNode.Attributes["Zip"].Value; //Outputs: 110092
 
}
}




Lets look at another XML:
string myXMl = "<root>" +
                 "<parent1>Some Data</parent1>" +
                 "<parent2>" +
                   "<Child1 id='1' name='d1'>data1</Child1>" +
                   "<Child2 id='2' name='d2'>data2</Child2>" +
                 "</parent2>" +
               "</root>";

XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(myXMl);
XmlNodeList xNodeList = xDoc.SelectNodes("root/child::node()");

//Traverse the entire XML nodes.
foreach (XmlNode xNode in xNodeList)
{
    //Looks for any particular nodes
   
if (xNode.Name == "parent1")
    {
        //some traversing....
   
}

    if (xNode.Name == "parent2")
    {
        //If the parent node has child nodes then
        //traverse the child nodes
       
foreach (XmlNode xNode1 in xNode.ChildNodes)
        {
           string childNodeName = xNode1.Name;      //Ouputs: Child1
          
string childNodeData = xNode1.InnerText; //Outputs: data1

           //Loop through each attribute of the child nodes
          
foreach (XmlAttribute xAtt in xNode1.Attributes)
           {
               string attrName = xAtt.Name;   //Outputs: id
              
string attrValue = xAtt.Value; //Outputs: 1
          
}
        }
    }
}

No comments:

Post a Comment