Published on: 15 Feb, 2014

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

Tumblr Digg Google Plus

In previous article, I have showed you on how to read basic xml document only. There is a slightly changes when you want to read xml documents that contains xml namespace. We will still use the same xml document example as listed below.

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

If you see carefully on the following code, in order to successfully read the xml that has namespace embedded, You will need to use XmlNamespaceManager and declare a namespace prefix. When selecting a node in xml document, you need to include this prefix for each node. See below code for more details.

XmlDocument doc = new XmlDocument();
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("ns", "");
XmlNode nodeResult = doc.SelectSingleNode("/ns:bookstore", ns);
if (nodeResult != null)
    XmlNodeList nodeList = doc.SelectNodes("/ns:bookstore/ns:book", ns);
    foreach (XmlNode node in nodeList)
        XmlNodeList childNodes = node.ChildNodes;
        foreach (XmlNode childNode in childNodes)
            Console.WriteLine(childNode.Name   " "   childNode.InnerText   "<br/>");


There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.