MaverickTM
MaverickTM

Reputation: 25

Parsing a XDocument

I have the following 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>

I am trying to return $CT_STQ_V2 if and only if the Attribute Name="STS" and ExtensionType="alarmextension"

How can I use XDocument & LINQ query to get what I need. I need to parse through thousands of XML files so fast performance would be required. Any suggestions would help.

Thank you.

Upvotes: 1

Views: 1192

Answers (1)

Hari Prasad
Hari Prasad

Reputation: 16956

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

Upvotes: 1

Related Questions