Parse an XML file

Posted by karan@dotnet on ASP.net Weblogs See other posts from ASP.net Weblogs or by karan@dotnet
Published on Fri, 30 Apr 2010 02:57:00 GMT Indexed on 2010/04/30 3:18 UTC
Read the original article Hit count: 595

Filed under:
|

The following code shows a simple method of parsing through an XML file/string. 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='John Mayer'" +
"Address='12th Street'" +
"City='New York' Zip='10004'>" +
"</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: John Mayer
string Address = xNode.Attributes["Address"].Value;
//Outputs: 12th Street
string City = xNode.Attributes["City"].Value;
//Outputs: New York
string Zip = xNode.Attributes["Zip"].Value;
//Outputs: 10004
}
}

Lets look at another XML:

string myXMl = "<root>" +
"<parent1>..some data</parent1>" +
"<parent2>" +
"<Child1 id='1' name='Adam'>data1</Child1>" +
"<Child2 id='2' name='Stanley'>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
}
}
}
}

 

© ASP.net Weblogs or respective owner

Related posts about c#

Related posts about Xml