基于具有特定属性的单个子元素获取父节点

时间:2015-02-16 13:54:07

标签: linq

我的xml以下

    <component>
                <!--Active Problems-->
                <section>
                    <templateId root="2.16.840.1.113883.3.88.11.83.103" assigningAuthorityName="HITSP/C83"/>
                    <templateId root="1.3.6.1.4.1.19376.1.5.3.1.3.6" assigningAuthorityName="IHE PCC"/>
                    <templateId root="2.16.840.1.113883.10.20.1.11" assigningAuthorityName="HL7 CCD"/>

                </section>
            </component>
<component> 
<!--Medications-->
                <section>
                    <templateId root="2.16.840.1.113883.3.88.11.83.112" assigningAuthorityName="HITSP/C83"/>
                    <templateId root="1.3.6.1.4.1.19376.1.5.3.1.3.19" assigningAuthorityName="IHE PCC"/>
                    <templateId root="2.16.840.1.113883.10.20.1.8" assigningAuthorityName="HL7 CCD"/>
                </section>
            </component>

从此我想读取包含templateId节点的节节点,其中根属性的值为2.16.840.1.113883.10.20.1.8。如何使用linq完成?

1 个答案:

答案 0 :(得分:1)

您可以使用Linq-to-XML轻松完成此操作。

使用此:

using System.Xml.Linq;  // required namespace for linq-to-xml
XDocument doc = XDocument.Load(@"mypath\myxmlfile.xml");

将XML文件加载到XDocument对象中。

然后使用以下查询:

 var section = from s in doc.Descendants("section")
               where s.Elements("templateId")
                      .Any(t => t.Attribute("root").Value == "2.16.840.1.113883.10.20.1.8")
               select s;

获取所需的<section>元素。

<强>输出:

- <section>
     <templateId root="2.16.840.1.113883.3.88.11.83.112" assigningAuthorityName="HITSP/C83" /> 
     <templateId root="1.3.6.1.4.1.19376.1.5.3.1.3.19" assigningAuthorityName="IHE PCC" /> 
     <templateId root="2.16.840.1.113883.10.20.1.8" assigningAuthorityName="HL7 CCD" /> 
  </section>
相关问题