Friday, December 14, 2012

XML Parsing in ASP.NET


Using the System.Xml name space we can parse and XML file to read the parent node, Child node and the attributes.

In below example Students is the parent node and Student is the child node. ID, Name, Address, City and STID are attributes.

private void ParsingXMLFile()

{
   string myXMl = "<Students>" +
                 "<Student ID='1' Name='Chamara' " +
                      "Address='305 Kandy' " +
                      "City='Kandy' STID='1005'> " +
                 "</Student>" +
               "</Students>";

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

        XmlNodeList xNodeList = xDoc.SelectNodes("Students/child::node()");
        foreach (XmlNode xNode in xNodeList)
        {
            if (xNode.Name == "Student")
            {
                string ID = xNode.Attributes["ID"].Value;
                Response.Write(ID + "<br/>");
                string Name = xNode.Attributes["Name"].Value;
                Response.Write(Name + "<br/>");
                string Address = xNode.Attributes["Address"].Value;
                Response.Write(Address + "<br/>");
                string City = xNode.Attributes["City"].Value;
                Response.Write(City + "<br/>");
                string STID = xNode.Attributes["STID"].Value;
                Response.Write(STID + "<br/>");
            }
        }
    }

Out put:
1
Chamara
305 Kandy
Kandy
1005

No comments:
Write comments
Recommended Posts × +