2017-09-23 52 views
1

获取值我试图从XML获得输入反应值:C#从XML响应

<?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> 

我的代码是:

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

var xDocument = XDocument.Parse(responseString); 

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

但我得到了A和responseNode空值。怎么了?由于

+0

尝试'var A = xDocument.XPathSelectElement(“/ A”);' –

+0

没有工作,仍然变为空 –

回答

2

公然无视这是你的XML文档中定义的XML命名空间:

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

您需要包含到您的查询 - 我想尝试做这样的:

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

如果您坚持使用XPathSelectElement方法,那么你必须定义一个XmlNamespaceManager,并在您的XPath使用它选择:

// 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); 
+0

哇,不知道它也很重要。谢谢 :) –