Querying xml child elements with prefixed namespace using LINQ to XML

syneptody picture syneptody · Oct 3, 2012 · Viewed 7.2k times · Source

So I have some XML that generally looks like this

<wd:Data xmlns:wd="urn:com.foo.bar/GetResult">
    <wd:Result>
        <wd:field1>lorem</wd:field1>
        <wd:field2>ipsum</wd:field2>
        <wd:field3>dolor</wd:field3>
        <wd:field4>sit</wd:field4>
    </wd:Result>
</wd:Data>

The namespace is prefixed with "wd"

I'd like to be able to take each of the elements within <wd:Result>...</wd:Result> and create a new KeyValuePair<string, string> where the key is the element name and the value is the value of the element like so:

{"field1", "lorem"} {"field2", "ipsum"} {"field3", "dolor"} {"field4", "sit"}

My struggle is with the namespace prefix. I am very much a novice with LINQ but I have always been able to get something like this to work with code like this:

var data = XElement.Parse(theXml); 
XNamespace ns = "urn:com.foo.bar/GetResults"; 
var result = data.Elements(ns + "Result")
                 .Select(x => new KeyValuePair<string, string>(x.Name.LocalName, x.Value))
                 .ToList();

How should I query this data to to produce the desired result?

I'm not married to LINQ so whatever the community feels is best will be fine with me.

Answer

syneptody picture syneptody · Oct 3, 2012

It turns out that I needed to combine Descendants() with Elements()

The following code acheived exactly what I was after:

    var data = XElement.Parse(theXml);  
    XNamespace ns = "urn:com.foo.bar/GetResults";  
    var result = data.Descendants(ns + "Result")
                     .Elements()
                     .Select(x => new KeyValuePair<string, string>(x.Name.LocalName, x.Value))
                     .ToList();