Search code examples
c#xmlselectsinglenode

C # SelectSingleNode - Can it be used recursively?


As in, if I have an XML Document

<root a="value">
    <item name="first">
        x
        <foo name = "firstgrandchild">There is nothing here</foo>
        y
        <foo name = "secondgrandchild">There is something here</foo> 
    </item>
    <item name="second">
        xy
        <foo/>
        ab
    </item>
</root>

I want to first find the first occurrence of node "item" and then update the attribute, and then I want to update the first occurrence of node "foo" and then update the attribute etc.,

My Code is as below

myDoc.Load("Items2.xml");
myNode = myDoc.DocumentElement;
mySearchNode = myNode.SelectSingleNode("/root/item");
mySearchNode.Attributes["name"].Value = "Joel";
Console.WriteLine(mySearchNode.OuterXml);
mySearchChildNode = mySearchNode.SelectSingleNode("/item/foo");
Console.WriteLine(mySearchChildNode.OuterXml);

While, the first search and update of attribute works fine, the second one fails as mySearchNode.SelectSingleNode returns null.

Question - Is there something fundamentally that is wrong with this code? Why does not the SelectSingleNode work as expected in the second instance, as far as it is concerned, I am executing it on a XmlNode of type Element.

Kindly assist.

Many Thanks,


Solution

  • Your second XPath query should be without the leading slash. / means "root of document". If you omit the slash, the query will be relative to your mySearchNode variable. You also should not include "item" again, your query is relative to the "item" node you selected. In code:

    myDoc.Load("Items2.xml");
    myNode = myDoc.DocumentElement;
    mySearchNode = myNode.SelectSingleNode("/root/item");
    mySearchNode.Attributes["name"].Value = "Joel";
    Console.WriteLine(mySearchNode.OuterXml);
    mySearchChildNode = mySearchNode.SelectSingleNode("foo");
    Console.WriteLine(mySearchChildNode.OuterXml);