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
You can use an XPath query:
var xPath = "/methodResponse/params/param/value/struct/member/name[text()='responseCode']/../value/i4";
var value = xDocument.XPathSelectElement(xPath).Value;
Notice how name[text()='responseCode']
is used to pick the right member
element. This will work even if the sequence of member
elements are changed or another member
appears as the last element.
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.