Search code examples
c#xpathxmldocument

XmlDocument XPath expression failing


I am using C# XmlDocument API.

I have the following XML:

<Node1>
    <Node2>
        <Node3>
        </Node3>
    </Node2>
</Node1> 

I want to get Node3 as an XmlNode. But my code is returning null:

XmlDocument doc = new XmlDocument();
doc.Load(reader);
XmlNode root_node = doc.DocumentElement.SelectSingleNode("/Node1");

Log(root_node.OuterXml);
XmlNode test_node = root_node.SelectSingleNode("/Node2/Node3");

if (test_node == null)
    Logger.Log.Error(" --- TEST NODE IS NULL --- ");

The log for root_node.OuterXml logs

<Node1><Node2><Node3>.....

But test_node returns null.

What is going wrong here?


Solution

  • Use the path "Node2/Node3" instead of "/Node2/Node3":

    XmlNode test_node = root_node.SelectSingleNode("Node2/Node3");
    

    In an XPath expression, a leading forward slash / represents the root of the document. The expression "/Node2/Node3" doesn't work because <Node2> isn't at the root of the document.