如何搜索具有匹配结束标记的xml标记?

2024-04-16 22:50:12 发布

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

我想知道在python中搜索和删除XML标记、其中的内容(不管是什么)以及结束标记的最佳方法是什么?XML也是格式良好的。你知道吗


Tags: 方法标记内容格式xml
1条回答
网友
1楼 · 发布于 2024-04-16 22:50:12

可以使用XPath标识元素,然后使用remove方法:

import xml.etree.ElementTree as ET
data = '''\
<node1>
  <node2 a1="x1"> ... </node2>
  <node2 a1="x2"> ... </node2>
  <node2 a1="x1"> ... </node2>
</node1>
'''
doc = ET.fromstring(data)
e = doc.find('node2/[@a1="x2"]')
doc.remove(e)
print(ET.tostring(doc))
# <node1>
#   <node2 a1="x1"> ... </node2>
#   <node2 a1="x1"> ... </node2>
# </node1>

相关问题 更多 >