使用 SelectSingleNode 获取属性值
Using SelectSingleNode to get an attribute value
我想使用 SelectSingleNode 获取节点的属性值。我已经检查过 here.
我已经尝试过这些选择器,但它们 return 是空引用异常:
node.SelectSingleNode("/@id").InnerText
node.SelectSingleNode("@id").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
如何通过SelectSingleNode
获取product
节点的'ID'属性值?
请注意 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
我想使用 SelectSingleNode 获取节点的属性值。我已经检查过 here.
我已经尝试过这些选择器,但它们 return 是空引用异常: node.SelectSingleNode("/@id").InnerText node.SelectSingleNode("@id").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
如何通过SelectSingleNode
获取product
节点的'ID'属性值?
请注意 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