CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Dec 2010
    Posts
    1

    Reading XDocument

    have tried to parse an XML file like this:

    <books>
    <book>
    <attr name="Moby Dick">Moby Dick is a classic</attr>
    <attr isbn="isbnNumber">123456789</attr>
    </book>
    </books>

    How can I get the value of "123456789"? I don't really need the first attribute.

    I tried reading these in a foreach loop getting XElements but I keep getting a NULL object exception.

    foreach(XElement xe in XDoc.Attribute("attr"))
    {
    string str = xe.Attribute("isbnNumber").Value // NULL EXCEPTION HERE
    }

    Thanks in advance...

  2. #2
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Reading XDocument

    Because "attr" is not an attribute, it is a node named attribute, which makes no sense. Instead, use this type of format (which does make sense)

    Code:
    <books>
      <book>
        <name>Moby Dick</name>
        <isbn>123456789</isbn>
      </book>
    </books>

  3. #3
    Join Date
    Nov 2010
    Posts
    42

    Re: Reading XDocument

    string str = xe.Attribute("isbnNumber").Value // NULL EXCEPTION HERE

    What if you added:

    if (xe.Attribute != null)
    {
    string str = xe.Attribute("isbnNumber").Value
    }

    Does that do anything. I prefer using XmlNode

    such like:
    XmlDocument doc = new xmlDocument();
    doc.Load(xml);
    foreach (XmlNode b in doc.DocumentElement.Attributes)
    {
    if (node != null)
    {
    string str = xe.Attribute("isbnNumber").Value
    }
    }

  4. #4
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Reading XDocument

    If you check for null then it will just do nothing. attr in the example is *not* an attribute, it is a node, and that is why it fails.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured