XmlNode.SelectSingleNode

Hi,

This section is taken from the msdn

XmlNode.SelectSingleNode Method (String)
.
.
.
Return Value
The first XmlNode that matches the XPath query or a null reference (Nothing in Visual Basic) if no
matching node is found. The XmlNode should not be expected to be connected "live" to the XML document.
That is, changes that appear in the XML document may not appear in the XmlNode, and vice versa.

The return value is a read/write object BUT the changes will take affect nonly after calling Save()

Is this correct Or is the XmlNode return from SelectSingleNode() is write only object



Answer this question

XmlNode.SelectSingleNode

  • Joseph Stalin

    It just return you node in the tree. This is not a new node. This is exactly the same node that you may found in the tree yourself by traversing the DOM tree.

    As soon as you get the node it doesn't matter how you get it with SelectSingleNode() or directly from the tree.

    This is different from Select() method, which returns you collection of nodes. and if you after calling Select() delete all nodes from the tree you still will have them in returned collection.



  • Sqnyy

    Hi Gil,

    Yes it's correct:

    The following XML:

    xs\travers.xml

    < xml version="1.0" encoding="utf-8" >
    - <root>
    <a attra="attra" />
    - <b attrb1="attrb1" attrb2="attrb2">
    bvalue
    - <c attrc="attrc">
    <d>dvalue</d>
    </c>
    <e attre="attre" />
    - <f attrc="attrc">
    fvalue
    - <g>
    <h>hvalue</h>
    gvalue
    </g>
    <i>ivalue</i>
    </f>
    </b>
    </root>
    When we run the following code

    static void selectSingle()

    {

    XmlDocument xdoc = new XmlDocument();

    xdoc.Load("xs\\travers.xml");

    XmlNode n = xdoc.SelectSingleNode(@"//d");

    Console.WriteLine(n.Name);

    n.InnerXml = "new value";

    xdoc.Save("temp.xml");

    }

    we will get this file.

    temp.xml:

    < xml version="1.0" encoding="utf-8" >
    - <root>
    <a attra="attra" />
    - <b attrb1="attrb1" attrb2="attrb2">
    bvalue
    - <c attrc="attrc">
    <d>new value</d>
    </c>
    <e attre="attre" />
    - <f attrc="attrc">
    fvalue
    - <g>
    <h>hvalue</h>
    gvalue
    </g>
    <i>ivalue</i>
    </f>
    </b>
    </root>


  • XmlNode.SelectSingleNode