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" ?> <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>
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(); doc.Load(Server.MapPath("/book.xml")); XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable); ns.AddNamespace("ns", "http://www.example.com/books"); 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/>"); } } }