-
December 15th, 2010, 08:47 PM
#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...
-
December 15th, 2010, 09:05 PM
#2
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>
-
December 15th, 2010, 09:06 PM
#3
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
}
}
-
December 15th, 2010, 09:57 PM
#4
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|