XPath to find nearest ancestor element that contains an element that has an attribute with a certain value

前端 未结 4 1048
轻奢々
轻奢々 2020-12-28 14:31

ancestor::foo[bar[@attr=\"val\"]]

I thought this would work, but it\'s not. I need to find the nearest foo element going up in the tree tha

4条回答
  •  佛祖请我去吃肉
    2020-12-28 14:44

    In my opinion the best answer was provided by the person who posed the question. His solution was supposed to return all the ancestor foos. He wants only the nearest one which is the one with position()=1, so his xpath expression needs to be slightly amended to:

    ancestor::foo[bar[@attr="val"] and position() = 1]
    

    If he writes that the ancestor::foo[bar[@attr="val"]] didn't return anything, so he had some other problem in his xml or in his assumption about the current element of his XPath evaluation context.

    The other answers (starting with //) do not really answer the question and even if they by chance met the need of someone, so they are not efficient: they choose ALL elements in the xml file, applying filter on them afterwards. While what the relative xpath proposed by me or the person who was asking this question is just going to search through few elements starting from the current node up to the parent and it's parent etc. - it will be very efficient even with large XML files.

提交回复
热议问题