XPath and Selecting a single node

后端 未结 4 1398
北荒
北荒 2021-02-08 06:57

I\'m using XPath in .NET to parse an XML document, along the lines of:

XmlNodeList lotsOStuff = doc.SelectNodes(\"//stuff\         


        
相关标签:
4条回答
  • 2021-02-08 07:33

    If "stuffChild" is a child node of "stuff", then your xpath should just be:

    XmlNode stuffChild = stuff.SelectSingleNode("stuffChild");
    
    0 讨论(0)
  • 2021-02-08 07:40

    The // you use in front of stuffChild means you're looking for stuffChild elements, starting from the root.

    If you want to start from the current node (decendants of the current node), you should use .//, as in:

    stuff.SelectSingleNode(".//stuffChild");
    
    0 讨论(0)
  • 2021-02-08 07:56

    Selecting single node means you need only the first element. So, the best solution is:

    XmlNode stuffChild = stuff.SelectSingleNode("descendant::stuffChild[1]");
    
    0 讨论(0)
  • 2021-02-08 07:57

    // at the beginning of an XPath expression starts from the document root. Try ".//stuffChild". . is shorthand for self::node(), which will set the context for the search, and // is shorthand for the descendant axis.

    So you have:

    XmlNode stuffChild = stuff.SelectSingleNode(".//stuffChild");
    

    which translates to:

    xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant::stuffChild");

    xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant-or-self::stuffChild");
    

    In the case where the child node could have the same name as the parent, you would want to use the slightly more verbose syntax that follows, to ensure that you don't re-select the parent:

    xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant::stuffChild");
    

    Also note that if "stuffChild" is a direct descendant of "stuff", you can completely omit the prefixes, and just select "stuffChild".

    XmlNode stuffChild = stuff.SelectSingleNode("stuffChild");
    

    The W3Schools tutorial has helpful info in an easy to digest format.

    0 讨论(0)
提交回复
热议问题