Canvas
Canvas

Reputation: 5897

Extract exact value from XML

I'm trying to get a XML value from some XML, here is my XML

<SearchResult>
  <Entity id="192418" defaultrole="TEMP_JOB_R">
    <Property name="JOB_GEN">
      <Attribute name="REFERENCE">192418</Attribute> 
    </Property>
  </Entity>
</SearchResult>

I have tried this

var reference = (
  from el in result.XPathSelectElements("Entity")
  select el.Attributes("REFERENCE").Select(x => x.Value).SafeParse<long>().FirstOrDefault()
);

However reference is always equal to 0 How can I select the reference attribute and pull back just its value?

Upvotes: 0

Views: 168

Answers (1)

har07
har07

Reputation: 89325

If you're interested in a solution using XPath expression, the following XPath will select <Attribute> elements having name attribute equals REFERENCE :

var reference = (from el in result.XPathSelectElements("//Entity/Property/Attribute[@name='REFERENCE']")
                 select (long)el
                 );

Or if you expect only single result :

var reference = (long)result.XPathSelectElement("//Entity/Property/Attribute[@name='REFERENCE']");

Side note: You can just cast XElement to long as demonstrated above.

Upvotes: 3

Related Questions