Published on: 15 Feb, 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" ?>
  <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
    <title>The Autobiography of Benjamin Franklin</title>
  <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
    <title>The Confidence Man</title>
  <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
    <title>The Gorgias</title>

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();
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);


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
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.