Chris Townsend
Chris Townsend

Reputation: 3162

How to use XElement.Parse and then find the value of a specific element?

I've got some XML that is returned from a REST call that looks like this:

<ArrayOfProperty xmlns=\"http://schemas.microsoft.com/HPCS2008R2/common\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">
  <Property>
    <Name>Id</Name>
    <Value>17</Value>
  </Property>
  <Property>
    <Name>StartTime</Name>
    <Value>11/7/2012 9:13:50 PM</Value>
  </Property>
  <Property>
    <Name>State</Name>
    <Value>Failed</Value>
  </Property>

I'm using the RestSharp API to assist in executing the API calls and trying to use the linq-to-xml XElement.Parse to parse the results. I'm not sure how to get the value of the state such that from within this document I want to do something like :

XElement.Parse(XMLstring).Elements??? to get the text "Failed" from the set of elements that contains the element State but I want the text "Failed" from the <Value>Failed</Value> element. That value element can have multiple values but I always want the value that is associated with the state.

Any ideas?

Upvotes: 1

Views: 2257

Answers (1)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56172

Your XML contains default namespace, so you need to define it and use in query.

XNamespace ns = "http://schemas.microsoft.com/HPCS2008R2/common";

var value = (string)XDocument.Parse(input)
    .Descendants(ns + "Property")
    .Where(p => (string)p.Element(ns + "Name") == "State")
    .Elements(ns + "Value").FirstOrDefault();

Upvotes: 1

Related Questions