Published on: 15 February, 2014

How to read xml document using XmlDocument in ASP.Net C#?

Tumblr Digg Google Plus

In C#, you can easily using XmlDocument object to read the xml. The xml data can be a file or an xml string. You will find below xml document as an example. It will list a collections of books contain details like title, ISBN, publication date, author and price.

<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
  <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
    <title>The Autobiography of Benjamin Franklin</title>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
    <price>8.99</price>
  </book>
  <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
  <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
    <title>The Gorgias</title>
    <author>
      <name>Plato</name>
    </author>
    <price>9.99</price>
  </book>
</bookstore>

Below is the sample code to read the xml document based on a file path location. Remember in order to use XmlDocument object, you will need to import System.Xml

XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("/bookplain.xml"));
XmlNode nodeResult = doc.SelectSingleNode("/bookstore");
if (nodeResult != null)
{
    XmlNodeList nodeList = doc.SelectNodes("/bookstore/book");
    foreach (XmlNode node in nodeList)
    {
        XmlNodeList childNodes = node.ChildNodes;
        foreach (XmlNode childNode in childNodes)
        {
            Console.WriteLine(childNode.Name  + " " +  childNode.InnerText);
        }
    }
}

Comments

Alex Fox
15 November, 2017
Hello! Please, tell me how to read the attributes of the elements? P.s. The number of attributes is not known
andy
16 November, 2017
Hi Alex, You can use the attributes key, see below example. XmlNodeList nodeList = doc.SelectNodes("/bookstore/book"); foreach (XmlNode node in nodeList) { string attributeValue = node.Attributes["attribute-name"].Value; }
Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.