簡體   English   中英

如何從C#中的XML字符串獲取特定節點

[英]how to get specific nodes from XML string in C#

我正在嘗試從下面的Web API XML響應中獲取“ cust_name”和“ code”節點。

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

我正在嘗試定位特定的節點,但收到“對象引用未設置為對象實例”的錯誤。 我在這里做錯了什么?

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

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

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

因此,例如,要獲取第一個客戶的名稱,您可以執行以下操作:

string name = customers.First().name;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM