简体   繁体   中英

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="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.

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();

Ok this is not a complete solution, but I think u should get basic idea around using Namespaces inside your XML and reading data with LINQ

lest say you already loaded your XML in memory, here is how u can access that

XDocument inventory = XDocument.Load("path_to_your_file.xml");

XNamespace vs = "urn:com.foo.bar/GetResult";
var names = doc.Descendants(vs + "Result")
           .Select(x => (string) x)
           .ToList();

this is not an exact implementation for you XML structure, but I think u get the idea how to work with namespaces

你也可以使用localname属性并做这样的事情

var names  = from n in xdoc.Descendants() where n.Name.LocalName == "Result" select n;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM