Search code examples
xmlxpathattributesselectsinglenode

Using SelectSingleNode to get an attribute value


I want to get a node's attribute value using SelectSingleNode. I already checked here.

I tried these selectors already but they return a null reference exception: node.SelectSingleNode("/@id").InnerText node.SelectSingleNode("@id").InnerText

Here's part of the XML I'm trying to parse:

<?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

How can I get the 'ID' attribute value of of the product node via SelectSingleNode?


Solution

  • Notice that XML is case-sensitive, so you should've used upper-case @ID instead :

    node.SelectSingleNode("@ID").InnerText
    

    Demo (in 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);
    }
    

    output :

    4de
    4dea