Search code examples
c#xmllinqlinq-to-xmlxml-rpc

LINQ to xml for xml-rpc


I've a xml like below:

<methodResponse>
  <params>
    <param>
      <value>
        <struct>
          <member>
            <name>originTransactionID</name>
            <value>
              <string>23915</string>
            </value>
          </member>
          <member>
            <name>responseCode</name>
            <value>
              <i4>0</i4>
            </value>
          </member>
        </struct>
      </value>
    </param>
  </params>
</methodResponse>

I want to check if any member has an element with name responseCode and if its there, I want to pick the value.

I can pick it like this:

var test = xDocument.Descendants("member").Elements("value").LastOrDefault().Value;

Its working because I know the response code is the last element of member, but I'm not sure if this is the right way to go. Although the xml is predefined but still is there any better to query this?

Thanks


Solution

  • Yes, you're right since you know that the element which you are looking for is at the last location thus LastOrDefault is working in your case but it's obviously not dynamic query for a real-world scenario.

    You can use FirstOrDefault though to find the first matching element in entire collection and get the value like this:-

    var test = (string)xDocument.Descendants("member")
                 .FirstOrDefault(x => (string)x.Element("name") == "responseCode")
                 ?.Element("value");
    

    Sample Fiddle.