简体   繁体   English

如何从C#中的XML字符串获取特定节点

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

I'm trying to get "cust_name" and "code" nodes from a web API XML response below. 我正在尝试从下面的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>

I'm writing the response as string to XMLDocument and trying to read from it. 我将响应作为字符串写到XMLDocument并尝试从中读取。 Below is my code 下面是我的代码

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

I'm trying to target specific nodes but getting "object reference not set to an instance of an object" error. 我正在尝试定位特定的节点,但收到“对象引用未设置为对象实例”的错误。 what am i doing wrong here? 我在这里做错了什么?

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")
    });

In this example an XElement is parsed from the input string. 在此示例中,从输入字符串中解析了XElement

A Namespace is also created using the attribute xmlns . 还使用属性xmlns创建Namespace Note how this is used when selecting elements. 请注意在选择元素时如何使用它。

All cust elements in the root element are selected and projected into a new anonymous type that currently declares a string name and an int code (you can extend this as needed). 选择根元素中的所有cust元素并将其投影到一个新的匿名类型中,该匿名类型当前声明一个string名称和一个int代码(您可以根据需要扩展它)。

So for example, to get the name of the first customer you could do the following: 因此,例如,要获取第一个客户的名称,您可以执行以下操作:

string name = customers.First().name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM