Using XPath in SelectSingleNode: Retrieving individual element from XML if it's present

前端 未结 1 1869
清酒与你
清酒与你 2021-02-13 14:44

My XML looks like :



       one
       two
                


        
相关标签:
1条回答
  • 2021-02-13 15:36

    I think you want:

    myXMLdoc.SelectSingleNode("/itemSet/Item[text()='two']")
    

    In other words, you want the Item which has text of two, not the itemSet containing it.

    You can also use a single dot to indicate the context node, in your case:

    myXMLdoc.SelectSingleNode("/itemSet/Item[.='two']")
    

    EDIT: The difference between . and text() is that . means "this node" effectively, and text() means "all the text node children of this node". In both cases the comparison will be against the "string-value" of the LHS. For an element node, the string-value is "the concatenation of the string-values of all text node descendants of the element node in document order" and for a collection of text nodes, the comparison will check whether any text node is equal to the one you're testing against.

    So it doesn't matter when the element content only has a single text node, but suppose we had:

    <root>
      <item name="first">x<foo/>y</item>
      <item name="second">xy<foo/>ab</item>
    </root>
    

    Then an XPath expression of "root/item[.='xy']" will match the first item, but "root/item[text()='xy']" will match the second.

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