2017-04-25 189 views
1

我想從下面的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; 
} 

我試圖針對特定的節點,但得到「對象引用未設置爲對象的實例」錯誤。我在這裏做錯了什麼?

+1

這是幾乎可以肯定,由於命名空間的一部分。任何你不想使用LINQ to XML的原因,這使得命名空間處理更簡單? –

+0

這裏的答案:http://stackoverflow.com/a/4171468/126995 – Soonts

+0

可能重複的[XmlDocument.SelectSingleNode和xmlNamespace問題](http://stackoverflow.com/questions/4171451/xmldocument-selectsinglenode-and-xmlnamespace -issue) – Soonts

回答

2
XElement xml = XElement.Parse(xmlString); 
XNamespace ns = (string)xml.Attribute("xmlns"); 
var customers = xml.Elements(ns + "cust") 
    .Select(c => new 
    { 
     name = (string)c.Element(ns + "cust_name"), 
     code = (int)c.Element(ns + "cust_type") 
      .Element(ns + "code") 
    }); 

在此示例中,從輸入字符串中解析出XElement

A Namespace也使用屬性xmlns創建。請注意在選擇元素時如何使用它。

根元素中的所有cust元素都被選中並投影到一個新的匿名類型中,該類型當前聲明瞭一個string名稱和一個int代碼(您可以根據需要擴展該代碼)。

因此,例如,讓你可以做以下的第一個客戶的名稱:

string name = customers.First().name; 
+0

感謝您的回答!那工作。但是我不得不在「string name = customers.First()。name.First()。Value」)的末尾加上「First()。value」來返回實際的innerXML值,否則它會返回一些對象路徑。 –