Query xml children with namespace prefix using LINQ to XML
So I have XML that usually looks like
<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> Namespace prefixed with "wd"
I would like to be able to take each of the elements inside <wd:Result>...</wd:Result> and create a new KeyValuePair<string, string> , where the key is the name of the element and the value is the value of this element:
{"field1", "lorem"} {"field2", "ipsum"} {"field3", "dolor"} {"field4", "sit"}
My struggle with the namespace prefix. I am very new to LINQ, but I could always get something like this to work with the 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 do I request this data to get the desired result?
I am not married to LINQ, so everything that the community feels will be best with me.
Turns out I needed to combine Descendants () with Elements ()
The following code got what I got 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(); Well, this is not a complete solution, but I think you should get a basic idea around using namespaces inside your XML and reading data using LINQ
so that you already load your XML into memory, here is how you can access it
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 your XML structure, but I think you have an idea how to work with namespaces