简体   繁体   English

从XML文档中获取特定数据

[英]Get specific data from XML document

I have xml document like this: 我有这样的xml文档:

<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). 我正在使用c#,我想通过所有“level3”,并且对于每个“level3”,我想读取attribute2,如果它说“true”,我想打印相应的attribute3(可以是“level3” “没有这些属性)。

I keep the xml in XmlDocument. 我将xml保存在XmlDocument中。 Then I keep all the "level3" nodes like this: 然后我保留所有“level3”节点,如下所示:

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

(document is the XmlDocument). (文档是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.. 我尝试用for..each通过xnList,但对我来说没有什么工作正常..

How can I do it? 我该怎么做?

Thanks a lot 非常感谢

Well I'd use LINQ to XML: 好吧,我使用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. LINQ到XML做各种事情比简单得多 XmlDocument API。 Of course, the downside is that it requires .NET 3.5... 当然,缺点是它需要.NET 3.5 ......

(By the way, naming elements attributeN is a bit confusing... one would expect attribute to refer to an actual XML attribute...) (顺便说一下,命名元素 attributeN有点令人困惑......人们会期望attribute引用实际的XML属性......)

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

You can use an XPath query. 您可以使用XPath查询。 This will give you a XmlNodeList that contains all <attribute3> elements that match your requirement: 这将为您提供一个XmlNodeList ,其中包含符合您要求的所有<attribute3>元素:

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: 您可以将上述xpath查询分为三个部分:

  1. " //level3 " queries for all descendant elements named <level3> . //level3 ”查询名为<level3>所有后代元素。
  2. " [attribute2 = 'true'] " filters the result from (1) and only keeps the elements where the child element <attribute2> contains the text true . [attribute2 = 'true'] ”过滤(1)的结果,只保留子元素<attribute2>包含文本true元素。
  3. " /attribute3 " takes the <attribute3> childnode of each element in the result of (2) . /attribute3 ”获取(2)结果中每个元素的<attribute3>节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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