Jean Paul
Jean Paul

Reputation: 31

How do I select a single node from an xml node list?

I have an XmlDocument object in C# that has a structure like this:

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>
</catalog>

I'm creating a book NodeList and looping through assigning to an authors string array. When I try

XmlNodeList xnl = xmlDocument.SelectNodes("//catalog/book");
for (int i = 0; i < xnl.Count; i++)
{
    authors[i] = xnl[i].SelectSingleNode("//author").InnerText;
}

I get a null reference exception. Why should the result of SelectSingleNode be null?

Upvotes: 1

Views: 3448

Answers (2)

try this,

var all_elements = xmldoc.DocumentElement.SelectNodes("//catalog/book/author");

        foreach(XmlNode sub_elements in all_elements)
        {
            if(sub_elements.InnerText != "")
            {
                string answer = sub_elements.InnerText;
            }
            else
            {
                //null text
            }
        }

Upvotes: 0

Abhay
Abhay

Reputation: 135

Try one of the below

for (int i = 0; i < xnl.Count; i++)
{
    authors[i] = xnl[i].SelectSingleNode("//author").value;
}

OR

for (int i = 0; i < xnl.Count; i++)
{
    authors[i] = xnl[i].Attributes["author"].value;
}

Upvotes: 2

Related Questions