Namespace problems querying with XElement

Today I was working on an old SharePoint 2007 project which heavily uses the SharePoint webservices. That implies using a lot of XML as input and output for those services. At one point I had to extract some info from the XML fragment being returned.

The function returned an XElement. This type of object can be queried via Linq, or you can use the Element / Elements methods to get elements from a node. My XML was structured like this:

<Results xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<Result ID="1,Update">
<ErrorCode>0x00000000</ErrorCode>
<ErrorText>Some text</ErrorCode>
</Result>
</Results>

This was all being returned as a XElement variable which I named “resultNode”. I wanted to fetch the ErrorText value, so I tried things like:

resultNode.Element("Result").Element("ErrorText")
resultNode.Elements("Result").First().Elements("ErrorText").First()

To cut a long story short; this all wasn’t working. The problem is caused by the document having a different default namespace (i.e. http://schemas.microsoft.com/sharepoint/soap/). This means all elements become prefixed with this namespace and you need to include it in your queries. You can do this like this:

resultNode.Element("Result") becomes:
resultNode.Element(resultNode.Name.Namespace + "Result");

There are probably ways to set the default namespace, or to remove the namespace completely so it doesn’t bother you (just make sure there aren’t multiple namespaces defined). But for simple things, this fixes the problem neatly.

Related posts

Latest posts

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *