【发布时间】: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 命名空间会一直相同吗?因为该服务不是由我们管理的。我们正在从不同的资源中使用它。