This gotcha has tripped me up before and I’m not sure where I found the answer last time, but this time I thought I’d blog the answer. My hope is it will help others from wasting time, including my future self (since I’ll likely run into it again).
Here’s the scenario: You’re using .NET to parse some XML and you’ve decided to use the new XLinq library because its compact, has a cool name and makes your code look advanced.
Below is the XML you need to parse (sampled from AtomEnabled)
<title>Example Feed</title> 2003-12-13T18:30:02Z John Doe urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6 urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a 2003-12-13T18:30:02Z Some text.
Now here’s the XLinq code you use to retrieve the feed’s title:
XDocument doc = XDocument.Parse(xmlString);
string titleValue = doc.Root.Element("title").Value;
To your surprise this results in an unhandled NullReferenceException: “Object reference not set to an instance of an object.”. Looking at the XML above it looks like the right path and if you rollover doc.Root in the Visual Studio debugger it shows the contents of the feed element as expected.
The issue is that the default XML namespace has been changed. If you look at the feed element, you can see that a new namespace has been added without declaring a prefix (xmlns=”http://www.w3.org/2005/Atom”). This is the reason your code is not finding the elements. You must declare and use that new namespace in code:
XDocument doc = XDocument.Parse(xmlString); XNamespace atom = "http://www.w3.org/2005/Atom"; string titleValue = doc.Root.Element(atom + "title").Value;
With the namespace declared and used when finding elements, you will have success in retrieving values. The hard part of what to do with the parsed XML is left up to you, but at least you’re not stuck anymore.
For more LINQ awesomeness, check out the .NET Framework Developer Center
“because its compact, has a cool name and makes your code look advanced.”
Thanks for the tip and the chuckle.
Serious business for sure: http://bit.ly/bEpMnY
Pingback: Dew Drop – July 15, 2010 | Alvin Ashcraft's Morning Dew
i don’t see the title element in your xml….
@Chris – good catch, it appears that the code highlighter wasn’t rendering the “title” tag. I’ve encoded the square brackets so the title tag is displayed.