Multiple namespaces when using LINQ to XML

In BizTalk

This blog post is about using LINQ to XML when the XML document has multiple namespaces defined. I’m using the Twitter API as example.

The sample XML

This is the partial XML result of the Twitter API query “http://search.twitter.com/search.atom?q=bergdaniel”. It includes a number of namespaces – the two most important being “http://www.w3.org/2005/atom” and “http://api.twitter.com/”.

Using LINQ to XML

In order to query the XML with LINQ we need to define the namespaces and pass them as parameters along with the element names. Since the “atom”-namespace is the default namespace all elements that are not prefixed with <correspondingNamespace:someElement> need to pass the “atom”-namespace as parameter. The elements that are prefixed with <twitter:elementName> need to have the “twitter”-namespace passed as parameter.

Important

Make sure that the namespace is defined exactly as it is in the XML. If you miss a trailing slash (“http://api.twitter.com” instead of “http://api.twitter.com/”) you’ll end up with an NullReferenceException like this:

image

daniel
daniel
Developer
Recent Posts
Contact Us

We're not around right now. But you can send us an email and we'll get back to you, asap.

Not readable? Change text. captcha txt

Start typing and press Enter to search