0

PythonでXMLタグ、その中のコンテンツ(それが何であれ)、およびその終了タグを検索および削除するための最良の方法は何ですか? XML も整形式です。

4

1 に答える 1

2

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>
于 2012-10-19T00:42:18.070 に答える