简体   繁体   中英

Get specific data from XML document

I have xml document like this:

<level1>
 <level2>
  <level3>
   <attribute1>...</attribute1>
   <attribute2>false</attribute2>
   <attribute3>...</attribute3>
  </level3>
  <level3>
   <attribute1>...</attribute1>
   <attribute2>true</attribute2>
   <attribute3>...</attribute3>
  </level3>
</level2>
<level2>
 <level3>
   <attribute1>...</attribute1>
   <attribute2>false</attribute2>
...
...
...

I'm using c#, and I want to go thru all "level3", and for every "level3", i want to read attribute2, and if it says "true", i want to print the corresponding attribute3 (can be "level3" without these attributes).

I keep the xml in XmlDocument. Then I keep all the "level3" nodes like this:

XmlNodeList xnList = document.SelectNodes(String.Format("/level1/level2/level3"));

(document is the XmlDocument).

But from now on, I don't know exactly how to continue. I tried going thru xnList with for..each, but nothing works fine for me..

How can I do it?

Thanks a lot

Well I'd use LINQ to XML:

var results = from level3 in doc.Descendants("level3")
              where (bool) level3.Element("attribute2")
              select level3.Element("attribute3").Value;

foreach (string result in results)
{
    Console.WriteLine(result);
}

LINQ to XML makes all kinds of things much simpler than the XmlDocument API. Of course, the downside is that it requires .NET 3.5...

(By the way, naming elements attributeN is a bit confusing... one would expect attribute to refer to an actual XML attribute...)

您可以使用LINQ to XML并阅读是一个好的开始。

You can use an XPath query. This will give you a XmlNodeList that contains all <attribute3> elements that match your requirement:

var list = document.SelectNodes("//level3[attribute2 = 'true']/attribute3");

foreach(XmlNode node in list)
{
    Console.WriteLine(node.InnerText);
}

You can split the above xpath query in three parts:

  1. " //level3 " queries for all descendant elements named <level3> .
  2. " [attribute2 = 'true'] " filters the result from (1) and only keeps the elements where the child element <attribute2> contains the text true .
  3. " /attribute3 " takes the <attribute3> childnode of each element in the result of (2) .

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