如何从C#中的XML字符串获取特定节点
问题描述:
我想从下面的Web API XML响应中获取“cust_name”和“code”节点。如何从C#中的XML字符串获取特定节点
<?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
。
A Namespace
也使用属性xmlns
创建。请注意在选择元素时如何使用它。
根元素中的所有cust元素都被选中并投影到一个新的匿名类型中,该类型当前声明了一个string
名称和一个int
代码(您可以根据需要扩展该代码)。
因此,例如,让你可以做以下的第一个客户的名称:
string name = customers.First().name;
+0
感谢您的回答!那工作。但是我不得不在“string name = customers.First()。name.First()。Value”)的末尾加上“First()。value”来返回实际的innerXML值,否则它会返回一些对象路径。 –
这是几乎可以肯定,由于命名空间的一部分。任何你不想使用LINQ to XML的原因,这使得命名空间处理更简单? –
这里的答案:http://stackoverflow.com/a/4171468/126995 – Soonts
可能重复的[XmlDocument.SelectSingleNode和xmlNamespace问题](http://stackoverflow.com/questions/4171451/xmldocument-selectsinglenode-and-xmlnamespace -issue) – Soonts