我想使用SelectSingleNode获取节点的属性值。我已经检查了here。
我已经尝试过这些选择器,但它们返回一个空引用异常: node.SelectSingleNode(" / @ ID&#34)。的innerText node.SelectSingleNode(" @ ID&#34)。的innerText
这是我尝试解析的XML的一部分:
<?xml version="1.0" encoding="utf-8"?>
<products>
<product ID="4de">
<name>Prod name</name>
</product>
<product ID="4dea">
<name>Prod name 2</name>
</product>
</products>
Dim productXML As New XmlDocument
Dim node As XmlNode
Dim root As XmlNode
productXML.LoadXml(responseString)
Dim mgr As XmlNamespaceManager = New XmlNamespaceManager(productXML.NameTable)
mgr.AddNamespace("test", productXML.DocumentElement.NamespaceURI)
root = productXML.DocumentElement
Dim nodeList As XmlNodeList = root.SelectNodes("/products/product")
'to get the product title (this works):
node.SelectSingleNode("name").InnerText
我如何获得&#39; ID&#39;通过product
生成SelectSingleNode
节点的属性值?
答案 0 :(得分:3)
请注意,XML区分大小写,因此您应该使用大写@ID
代替:
node.SelectSingleNode("@ID").InnerText
演示(在C#中):https://dotnetfiddle.net/TWMUlD
var xml = @" <products>
<product ID='4de'>
<name>Prod name</name>
</product>
<product ID='4dea'>
<name>Prod name 2</name>
</product>
</products>";
var root = new XmlDocument();
root.LoadXml(xml);
var nodeList = root.SelectNodes("/products/product");
foreach (XmlNode node in nodeList)
{
var id = node.SelectSingleNode("@ID").InnerText;
Console.WriteLine(id);
}
输出
4de
4dea