解析XDocument

时间:2016-08-30 03:53:14

标签: c# linq linq-to-xml

我有以下XDocument:

<ExtensionInfo>
  <ObjectExtension />
  <AttributeExtension>
    <Attribute Name="PV" ExtensionType="inputoutputextension" InheritedFromTagName="$CT_STQ_V2" />
    <Attribute Name="PV" ExtensionType="logdatachangeeventextension" InheritedFromTagName="$CT_STQ_V2" />
    <Attribute Name="STS" ExtensionType="inputoutputextension" InheritedFromTagName="$CT_STQ_V2" />
    <Attribute Name="STS" ExtensionType="booleanextension" InheritedFromTagName="$CT_STQ_V2" />
    <Attribute Name="STS" ExtensionType="alarmextension" InheritedFromTagName="$CT_STQ_V2" />
    <Attribute Name="STS" ExtensionType="logdatachangeeventextension" InheritedFromTagName="$CT_STQ_V2" />
  </AttributeExtension>
</ExtensionInfo>

当且仅当属性名称=“STS”且ExtensionType =“alarmextension”时,我才会返回$ CT_STQ_V2

我如何使用XDocument&amp; LINQ查询得到我需要的东西。我需要解析数以千计的XML文件,因此需要快速的性能。任何建议都会有所帮助。

谢谢。

1 个答案:

答案 0 :(得分:1)

You could achieve this with simple Linq to Xml statements, my preferred choice dealing with large Xmls .

  XDocument doc = XDocument.Load(filename);

  var element = doc
      .Descendants("AttributeExtension")  // flatten the structure and look for extensions.
      .Elements("Attribute")              // get all attribute elements 
      .FirstOrDefault(x=>(string)x.Attribute("Name") == "STS" && (string)x.Attribute("ExtensionType") == "alarmextension");

  if(element!= null)
  {
      // return attribute value. 
      return (string)element.Attribute("InheritedFromTagName");
  }

Check this Demo