8

我想我忽略了一些简单的事情,但是我很难从 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="...">
4

1 回答 1

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());
于 2013-05-10T19:46:38.693 回答