syneptody syneptody - 1 year ago 76
C# Question

Querying xml child elements with prefixed namespace using LINQ to XML

So I have some XML that generally looks like this

<wd:Data xmlns:wd="">

The namespace is prefixed with "wd"

I'd like to be able to take each of the elements within
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 = "";
var result = data.Elements(ns + "Result")
.Select(x => new KeyValuePair<string, string>(x.Name.LocalName, x.Value))

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 Source

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 = "";  
    var result = data.Descendants(ns + "Result")
                     .Select(x => new KeyValuePair<string, string>(x.Name.LocalName, x.Value))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download