按标签查找节点,但不查找具有相同标签 Xpath python3.4 的子节点

find node by tag but not its children with the same tag Xpath python3.4

我有 xml 个文件,例如:

<root>
    <book>
        <first>
           <book>1</book>
           <book>2</book>
        </first>
     </book>
 </root>

使用 Xpath (predicates = tree.xpath('//book')) 我可以找到所有书籍节点(3 个节点),例如:

<book>
    <first>
       <book>1</book>
       <book>2</book>
    </first>
 </book>
 <book>1</book>
 <book>2</book>

但是如何找到其父节点不是书节点的书节点呢?即,如果找到节点书,则不要查看其子节点以查找更多书节点。 在我的示例中,我应该只有:

<book>
    <first>
       <book>1</book>
       <book>2</book>
    </first>
 </book>

谢谢

简单使用

tree.xpath('//book[not(ancestor::book)]'))

这不会 select book 元素嵌套到其他 book 元素中。我假设

find the book nodes that its parent is not a book node

你实际上是想找到 book 没有 祖先的元素 book 元素。

这是正确的 XPath 表达式,我无法评论您的代码,因为您没有显示它。