XPath: Default to 'Node A', select 'Node B' instead if 'Node B' is not empty

前端 未结 3 1416
忘了有多久
忘了有多久 2021-02-20 00:15

I need to create an XPath expression that does the following:

  • Returns the element inside of \'NodeA\' by default
  • Returns the element inside of \'NodeB\' i
3条回答
  •  一个人的身影
    2021-02-20 00:53

    If it is safe to rely on the fact that any NodeA's will come before NodeB in document order (as implied by your sample), then a simpler and much more efficient XPATH expression to select the required element is...

    (//my:NodeA[text()]|//my:NodeB)[1]
    

    The above selects the element. If you want to select the text node of the element, then use instead...

    (//my:NodeA[text()]|//my:NodeB)[1]/text()
    

    If there is no positional relationship between NodeA and NodeB (they can come in any relative order), and you are using XPATH 2.0, then the following expression will select the required text node..

    (//my:NodeA[text()],//my:NodeB)[1]/text()
    

提交回复
热议问题