thewarri0r9 thewarri0r9 - 25 days ago 7
C# Question

c# get values from xml response

I am trying to get values from xml respone :

<?xml version="1.0" encoding="utf-8"?>
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://adaddaasd.com">
<A>14</A>
<B>Failed</B>
<C>22</C>
</Response>


My code is :

string responseString = await response.Content.ReadAsStringAsync();

var xDocument = XDocument.Parse(responseString);

var responseNode = xDocument.XPathSelectElement("/Response");
var A = xDocument.XPathSelectElement("/Response/A");


But I am getting null values for A and responseNode. Whats wrong? Thanks

Answer Source

You're blatantly ignoring the XML namespace that's defined in your XML document:

<Response xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' 
          xmlns:xsd='http://www.w3.org/2001/XMLSchema' 
          xmlns='http://adaddaasd.com'>
          ****************************

You need to include that into your querying - I would try to do it like this:

var xDocument = XDocument.Parse(responseString);

// *define* your XML namespace!
XNamespace ns = "http://adaddaasd.com";

// get all the <Response> nodes under the root with that XML namespace
var responseNode = xDocument.Descendants(ns + "Response");

// from the first <Response> node - get the descendant <A> nodes
var A = responseNode.FirstOrDefault()?.Descendants(ns + "A");

If you insist on using the XPathSelectElement method, then you must define an XmlNamespaceManager and use it in your XPath select:

// define your XML namespaces
XmlNamespaceManager xmlnsmgr = new XmlNamespaceManager(new NameTable());
xmlnsmgr.AddNamespace("ns", "http://adaddaasd.com");

// use the defined XML namespace prefix in your XPath select
var A = xDocument.XPathSelectElement("/ns:Response/ns:A", xmlnsmgr);