Skip to content

Reading XDocument with namespaces

June 6, 2011

Building WP7 Apps i am forever producing and consuming webservices, the two most compatiable formats across the web that I deal with are XML and JSON. Normally XML is fairly easy but today I stumbled across a document that had me scratching my head.

<myns:response xmlns:myns=”http://www.mysite.com/ns/test” >
<myns:result>SUCCESS</myns:result>
</myns:response>

Normally if you want the result you would do something like this….

XDocument doc = XDocument.Parse(xml);
var result = doc.Element(“response”);

This of course is not going to work, what we need to do is declare a Namespace Prefix and you will have your answer.

1. Add a namespace declaration

private static readonly XNamespace myns = “http://www.mysite.com/ns/test“;

2. Update to include the namespace

var result = doc.Element(myns +”response”);

and done, now get back work…..

Advertisements
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: