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

前端 未结 3 1401
忘了有多久
忘了有多久 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:56

    A correct XPath expression is:

    (//my:NodeB[node()] | //my:NodeA[not(//my:NodeB/node())])/node()
    

    As the conditions in the predicates are mutually exclusive, only one of them can be true() and this guarantees that only one of the two nodes is selected by the expression within the brackets.

    So, the expression above selects any node that is a child of: my:NodeB if it has children, or my:NodeA -- otherwize.

    Here we assume as given that at most one element named my:NodeA and at most one element named my:NodeB exist in the XML document.

    Another assumption is that the namespace to which the prefix my is bound has been "registered" with the XPath expression evaluator (the specific XPath implementation you are using).

    Do note that in the provided XML document neither of the elements my:NodeA and my:NodeB has any element children (they both have just a text node child) -- so I assume that by "element" you actually mean "node".

提交回复
热议问题