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=""
xmlns:xsd="" xmlns="">

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='' 

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 = "";

// 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", "");

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