Possible Duplicate:
Use Linq to Xml with Xml namespaces
I have an xml:
<?xml version="1.0" encoding="UTF-8"?>
<string xmlns="http://tempuri.org/">
<Global>
<Items>
<Item text="Main text" key="1">
<Item text="Some text" key="1.1"/>
<Item text="Other text" key="1.2"/>
<Item text="Text" key="1.3"/>
</Item>
<Item text="Main text 2" key="2">
<Item text="Some text" key="2.1"/>
<Item text="Other text" key="2.2"/>
<Item text="Text" key="2.3"/>
</Item>
</Items>
</Global>
</string>
I need to get items inside Item (like with keys 2.1,1.1 etc).
I have this code:
var xml = GetXmlFromWeb(service.ServiceLink, true);
var stringXml = new StringReader(xml); // Load data from web)
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
var reader = XmlTextReader.Create(stringXml, settings);
XDocument docWithDecode = XDocument.Load(reader);
IEnumerable<XElement> elements = docWithDecode.Root.Descendants("Item");
As result i got Count = 0.
Thats interesting, if i write IEnumerable<XElement> elements = docWithDecode.Root.Descendants(); i got the elemets, but the sructure looks like mess, data was dublicated, each item has namespace refference etc. So something is wrong here.
Can somebody help me to write the working code? Thanks!
As I mentioned in the comments and L.B. mention in his answer, your
.Count()== 0 problem is due to the lack of a namespace. See this answer that I linked above to explain it in more details, but effectively your problem is you are searching for an element call “Item” but in fact what you are actually trying to find is namespace + “Item”. You just need to add the namespace to the query.After re-reading your question, I just noticed a problem with your XML and your query. You have an node with several child nodes with the same name. If you use
Descendants(), you are going to select all 8, rather than the 6 you specified in your question.To only select the child
<Item>Nodes, you need to modify your query sinceDescendants()will select anything that matches. You actually need to make use of the.Elements()extension method and select each level specifically.You can also use
Descendants(ns + "Items")instead of the first 2Elements()in the query since it doesn’t repeat inside itself.