Tim*_*Tim 8 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>
Run Code Online (Sandbox Code Playgroud)
我以为我可以使用所有三个观察节点
foreach (XElement element in Content.Descendants("observation"))
ExamineObservation(element);
Run Code Online (Sandbox Code Playgroud)
虽然看起来这只适用于观察没有孩子的情况.我也试过.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="...">
Run Code Online (Sandbox Code Playgroud)
我刚刚在VS2012中运行了这个代码,它命中了Console.WriteLine()3次,正确地输出了观察节点和内容:
XElement content = XElement.Parse(yourXmlStringWithNamespaceHeader);
foreach (XElement obs in content.Descendants("observation"))
Console.WriteLine(obs.ToString());
Run Code Online (Sandbox Code Playgroud)
编辑 - 考虑新的命名空间信息,并使用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());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5371 次 |
| 最近记录: |