Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grab value using XDocument

I have this xml from which I am trying to grab the value in the node <ErrorCode> after investigating, i found it easier to use XDocument because it cleans any unwanted \r\n that the response from an api was giving me.. but now I am not sure how to retrieve that value using XDocument

<PlatformResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://platform.intuit.com/api/v1">
  <ErrorMessage>OAuth Token rejected</ErrorMessage>
  <ErrorCode>270</ErrorCode>
  <ServerTime>2012-06-19T03:53:34.4558857Z</ServerTime>
</PlatformResponse>

I want to be able to take advantage of this call to get the value

 XDocument xmlResponse = XDocument.Parse(response);

I can't use XmlDocument because it does not clean the XML as it is doing it XDocument

Thank you

like image 277
user1416156 Avatar asked Dec 26 '22 22:12

user1416156


1 Answers

Since you have defined the Namespace, try the following code:

    XDocument xmlResponse = XDocument.Load("yourfile.xml");
    //Or you can use XDocument xmlResponse = XDocument.Parse(response)
    XNamespace ns= "http://platform.intuit.com/api/v1";
    var test = xmlResponse.Descendants(ns+ "ErrorCode").FirstOrDefault().Value;

Or if you don't want to use Namespace then:

    var test3 = xmlResponse.Descendants()
                .Where(a => a.Name.LocalName == "ErrorCode")
                .FirstOrDefault().Value;
like image 106
Habib Avatar answered Jan 08 '23 12:01

Habib