【问题标题】:how to get specific nodes from XML string in C#如何从 C# 中的 XML 字符串中获取特定节点
【发布时间】:2017-04-25 15:05:57
【问题描述】:

我正在尝试从下面的 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;
}

我正在尝试以特定节点为目标,但出现“对象引用未设置为对象实例”错误。我在这里做错了什么?

【问题讨论】:

  • 这几乎可以肯定是由于命名空间部分。有什么理由不想使用 LINQ to XML,这使得命名空间处理变得相当简单?
  • @Jon Skeet 这是一个大型应用程序的一部分,并且在应用程序的任何地方都没有使用 linq。反正我不能通过 Xpath 获取特定节点的值吗?
  • @Sonts 命名空间会一直相同吗?因为该服务不是由我们管理的。我们正在从不同的资源中使用它。

标签: c# xml


【解决方案1】:
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 是从输入字符串中解析出来的。

Namespace 也是使用属性xmlns 创建的。请注意在选择元素时如何使用它。

选择根元素中的所有 cust 元素并将其投影到一个新的匿名类型中,该类型当前声明了一个 string 名称和一个 int 代码(您可以根据需要对其进行扩展)。

例如,要获取第一个客户的姓名,您可以执行以下操作:

string name = customers.First().name;

【讨论】:

  • 感谢您的回答!那行得通。但我必须将“First().value”添加到“string name = customers.First().name.First().Value”的末尾,因为它返回实际的 innerXML 值,否则它会返回一些对象路径。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-20
相关资源
最近更新 更多