How to get node by name?
It's a simple task, but I can't make it work. Given the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<product>
<item1></item1>
<item2></item2>
<item3></item3>
</product>
I'd like to get all nodes within product
. Following two attempts return no nodes, I don开发者_开发技巧't see why:
XDocument meteoDoc = XDocument.Load("data.xml");
foreach (var item in meteoDoc.Descendants("product")) {//...}
foreach (var item in meteoDoc.Descendants().Where(x => x.Name == "product").Nodes()) {//...}
The following, as expected, would return me all nodes:
foreach (var item in meteoDoc.DescendantNodes()) { //...}
Thx for any tipps, I can't see the problem... :-/
Your first attempt is asking for all the Descendants
called product
. Your second attempt is finding the direct child nodes of all descendants called product
.
It's possible that it's looking for descendants within the root element... if you know that the root element is called product
, you could just use:
foreach (var item in meteoDoc.Root.Descendants())
(I can't test your existing code to find out exactly why it's not working for you right now, I'm afraid.)
Note that Descendants
will only find descendant elements - if you want all descendant nodes, you need the DescendantNodes
method.
Use this:
XDocument meteoDoc = XDocument.Load("data.xml");
foreach (var item in meteoDoc.Root.Descendants())
{
// ...
}
Try this:
foreach (var item in meteoDoc.Descendants("product"))
{
foreach (var prod in item.Descendants())
{
// do something
}
}
I have made a few change to xml, in this way the data is more well-formed and i can give you a piece of code that accomplish your task.
static void Main(string[] args)
{
//Data.xml
/*
<?xml version="1.0" encoding="UTF-8"?>
<product>
<item>
<name>test</name>
</item>
<item>
<name>test2</name>
</item>
<item>
<name>test3</name>
</item>
</product>
*/
XDocument meteoDoc = XDocument.Load("data.xml");
var result = from c in meteoDoc.Descendants("item")
select new { Name = c.Element("name").Value };
foreach (var item in result)
{
Console.WriteLine(item.Name);
}
精彩评论