我想從下面的Web API XML響應中獲取「cust_name」和「code」節點。如何從C#中的XML字符串獲取特定節點
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cust_list xmlns="http://example.com">
<cust>
<cust_id>1234</cust_id>
<cust_name>abcd</cust_name>
<cust_type>
<code>2006</code>
</cust_type>
</cust>
</cust_list>
我正在將響應作爲字符串寫入XMLDocument並嘗試從中讀取。下面是我的代碼
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://serviceURI");
request.Method = "GET";
request.ContentType = "Application/XML";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
string responseValue = reader.ReadToEnd();
var doc = new XmlDocument();
doc.LoadXml(responseValue);
string node = doc.SelectSingleNode("/cust_list/cust/cust_name").InnerText;
string node2 = doc.SelectSingleNode("/cust_list/cust/cust_type/code").InnerText;
}
我試圖針對特定的節點,但得到「對象引用未設置爲對象的實例」錯誤。我在這裏做錯了什麼?
這是幾乎可以肯定,由於命名空間的一部分。任何你不想使用LINQ to XML的原因,這使得命名空間處理更簡單? –
這裏的答案:http://stackoverflow.com/a/4171468/126995 – Soonts
可能重複的[XmlDocument.SelectSingleNode和xmlNamespace問題](http://stackoverflow.com/questions/4171451/xmldocument-selectsinglenode-and-xmlnamespace -issue) – Soonts