2017-09-23 59 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

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