繁体   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