在XDocument中递归查找节点

时间:2013-05-10 01:01:47

标签: c# xml linq-to-xml

我认为我忽略了一些简单的事情,但是我很难递归地从XDocument中提取节点。

我有类似的XML:

<?xml version="1.0" encoding="iso-8859-1"?>
<content>
  <operation></operation>
  <entry>
    <observation>
      <templateId/>
      <code></code>
      <value></value>
      <entryRelationship>
        <observation>
          <templateId/>
          <code></code>
          <value></value>
        </observation>
      </entryRelationship>
      <entryRelationship>
        <observation>
          <templateId/>
          <code></code>
          <value></value>
        </observation>
      </entryRelationship>
    </observation>
  </entry>
</content>

我以为我可以使用

获取所有三个观察节点
foreach (XElement element in Content.Descendants("observation"))
    ExamineObservation(element);

虽然看起来这只适用于观察没有孩子的情况。我也试过.Ancestors和.DecentantNodes,但没有得到我想要的。

我可以轻松编写一个递归方法来获取我需要的东西,但是如果有的话,我宁愿使用现有的方法,特别是因为我将在几个项目中使用XML。我错过了一些明显的东西吗?

请注意,任何说观察的节点,我都需要从中获取代码和值,因此在下面的示例中我将需要处理三个观察节点。观察节点的嵌套和数量是任意的。

感谢您的帮助。

附录

我发现我可能没有提供有关XML的足够信息。我不认为标签会有所作为,但我想我应该包括它们以防万一。下面是我试图解析的实际消息的前几行。为了隐私,我确实用“......”替换了一些文本。

<?xml version="1.0" encoding="iso-8859-1"?>
<content xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <operation>update</operation>
  <entry xmlns="urn:hl7-org:v3">
    <observation classCode="OBS" moodCode="EVN">
      <templateId root="..." />
      <code code="..." codeSystem="..." codeSystemName="..." displayName="...">
      </code>
      <value xsi:type="..." code="..." codeSystem="..." codeSystemName="..." displayName="...">
      </value>
      <entryRelationship typeCode="...">
        <observation classCode="..." moodCode="...">

1 个答案:

答案 0 :(得分:8)

我刚刚在VS2012中运行了这段代码,它点击了Console.WriteLine() 3次,正确地输出了观察节点和内容:

        XElement content = XElement.Parse(yourXmlStringWithNamespaceHeader);
        foreach (XElement obs in content.Descendants("observation"))
            Console.WriteLine(obs.ToString());

修改 - 考虑新的命名空间信息,并使用XDocument代替XElement

        XNamespace nse = "urn:hl7-org:v3";
        XDocument content = XDocument.Parse(yourXmlStringWithNamespaceHeader);
        foreach (XElement ele in content.Descendants(nse + "observation"))
            Console.WriteLine(ele.ToString());