(在Python中的)XPath:我想要选择一个没有“body”作为其祖先的节点

2024-09-29 02:22:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想选择一个没有作为其祖先的节点。你知道吗

例如

<root>
  <e>
    <head>
       <id>3</id>
       <word>abandon</word>
    </head>
    <body>
       <head>
          <word>accept</word>
       </head>
    </body>
  </e>
</root>

我要选择第一个元素,而不是第二个元素。你知道吗

我试过:

import xml.etree.ElementTree as ET

root = ET.fromstring(fin).getroot()
word = root.find('.//word[not(ancestor::body)]')

但它不起作用。你知道吗


Tags: importid元素节点asbodyrootxml
1条回答
网友
1楼 · 发布于 2024-09-29 02:22:47

可以将XPath 1.0lxml一起使用:

import lxml.etree as ET

fin = '''\
<root>
  <e>
    <head>
       <id>3</id>
       <word>abandon</word>
    </head>
    <body>
       <head>
          <word>accept</word>
       </head>
    </body>
  </e>
</root>'''


root = ET.fromstring(fin)
word = root.xpath('.//word[not(ancestor::body)]')
print(ET.tostring(word[0]))
# <word>abandon</word>

相关问题 更多 >