SelectSingleNode in XML for select second element doesn't work in C#

I have problem to select second node from root element in following example xml code:

<?xml version="1.0"?>
<config>
    <FirstNode>
        <ShowBlahBlah>
        </ShowBlahBlah>
    </FirstNode>
    <SecondNode>
        <ShowBlahBlah>
        </ShowBlahBlah>
    </SecondNode>
</config>

and using this C# code to select SecondNode:

XmlDocument doc = new XmlDocument();
doc.LoadXml(sReadXML);
XmlNode sChangesLog = doc.SelectSingleNode("config").SelectSingleNode("//SecondNode").SelectSingleNode("//ShowBlahBlah")
XmlNodeList sChildNodes = sChangesLog.ChildNodes;

but it selecting first node and return its value! how can I fix this problem?

Jon Skeet
people
quotationmark

You're using // at the start of each of your selections - which means "find descendant nodes starting at the root" (so the context is irrelevant). You could either do things in one step as per Jeffrey's answer, or use relative paths:

doc.SelectSingleNode("config")
   .SelectSingleNode("SecondNode")
   .SelectSingleNode("ShowBlahBlah")

Personally I'd use LINQ to XML instead, if at all possible:

var doc = XDocument.Parse(sReadXml);
var changes = doc.Root.Element("SecondNode").Element("ShowBlahBlah");

LINQ to XML is generally a much cleaner API than XmlDocument et al.

people

See more on this question at Stackoverflow