IMG-LOGO

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

andy - 15 Feb, 2014 7267 Views 2 Comment

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 Nov, 2017
Hello! Please, tell me how to read the attributes of the elements? P.s. The number of attributes is not known
andy
16 Nov, 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.

Related Articles

How to remove html tags from string in c#?

Sometimes you need to remove HTML tags from string to ensure there are no dangerous or malicious scripts especially when you want to store the string or data text into the database.