0

I have an XML document I am trying to query with LINQ to XML. The XML is ..

<?xml version="1.0" encoding="UTF-8"?>
<response>
  <operation>
    <authentication>
      <username>redacted</username>
      <isauthenticated>true</<isauthenticated>>
    </authentication>
    <result>
      <status>success</status>
      <other-elements></<other-elements>
      <other-elements></<other-elements>
      <other-elements>
        <other-sub-elements></other-sub-elements>
        <other-sub-elements></other-sub-elements>
      </<other-elements>
    </result>
  </operation>
</response>

I am trying to read the value of the node <status> to determine if the API call was successful. I am having trouble putting together the LINQ syntax necessary to grab the value of the <status node. I thought I could use XPath syntax as such to grab the value.

XDocument xml = XDocument.Parse(xmlResponse);
string returnValue = = xml.Descendants("result/status").Select(x => x.Name).ToString(); 

However, I am getting the following error ..

The '/' character, hexadecimal value 0x2F, cannot be included in a name.

1
  • xml.Descendants("status).Where(n => n.Parent.LocalName = "result") or something along xml.Descendants("result").Elements("result") Commented Jan 11, 2018 at 16:27

2 Answers 2

2

Try this code:

XDocument xdoc = XDocument.Parse(@"
<response>
  <operation>
    <authentication>
      <username>redacted</username>
      <isauthenticated>true</isauthenticated>
    </authentication>
    <result>
      <status>success</status>
    </result>
  </operation>
</response>

");

Boolean isSuccess;
String s = xdoc.Element("response").Element("operation").Element("result").Element("status").Value;

isSuccess = s == "success";

It gets the value of the status element and checks whether it is equal to a specific value; in this case, isSuccess will be true.

Sign up to request clarification or add additional context in comments.

Comments

1

The LINQ-to-XML methods Elements() and Descendants() only deal with single names, not xpath-like paths. If you want to give an xpath expression, use the xpath extensions.

// using System.Xml.Linq;
var status = (string)xml.XPathSelectElement("//result/status");

Otherwise you need to build up an equivalent query using the methods correctly.

var status = (string)xml.Descendants("result").Elements("status").FirstOrDefault();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.