Search code examples
c#xmlxmldocument

XMLDocument Class - Child Nodes - Abbreviated Load versus Full Load


I am exploring the XMLDocument Class

https://msdn.microsoft.com/en-us/library/system.xml.xmldocument(v=vs.110).aspx

I am using the above site to type in examples. I typed in the example to get child nodes and it works. My question is why doesn't it work when I use the full XML document that contains along more than one book added. What about the code needs to be modified to make it work when I use it with a full XML Document.

 XmlDocument doc = new XmlDocument();
    doc.LoadXml("<book ISBN='1-861001-57-5'>" +
                "<title>Pride And Prejudice</title>" +
                "<price>19.95</price>" +
                "</book>");

    XmlNode root = doc.FirstChild;

    //Display the contents of the child nodes.
    if (root.HasChildNodes)
    {
      for (int i=0; i<root.ChildNodes.Count; i++)
      {
        Console.WriteLine(root.ChildNodes[i].InnerText);
      }
    }

The full XML Load that I am using is below. It was copied from https://msdn.microsoft.com/en-us/library/system.xml.xmldocument(v=vs.110).aspx

 doc.LoadXml("<?xml version=\"1.0\"?> \n" +
"<books xmlns=\"http://www.contoso.com/books\"> \n" +
"<book genre=\"novel\" ISBN=\"1-861001-57-8\"publicationdate=\"1823-01- 
  28\">\n"+
"    <title>Pride And Prejudice</title> \n" +
"    <price>24.95</price> \n" +
"  </book> \n" +
"<book genre=\"novel\" ISBN=\"1-861002-30-1\"ublicationdate=\"1985-01- 
  01\">\n" +
"    <title>The Handmaid's Tale</title> \n" +
"    <price>29.95</price> \n" +
"  </book> \n" +
"</books>");

Solution

  • Since first node is <?xml version="1.0"?>, the books are not in doc.FirstChild but in doc.DocumentElement;

    XmlNode root = doc.DocumentElement;
    

    In your sample xml, the root of the document is book and child nodes are title and price. But if you want to have multiple books each child node is a book, not a title or price, so you need to access those by name or iterate to get the next level.

    foreach(XmlNode book in root)
    {
        Console.WriteLine("Title: {0}\r\nPrice: {1}", 
            book["title"].InnerText,
            book["price"].InnerText);
    }
    

    Or alternatively:

    foreach (XmlNode book in root)
    {
        foreach (XmlNode attribute in book)
        {
            Console.WriteLine(attribute.InnerText);
        }
    }