gpt4 book ai didi

python - 如何删除 XML 元素而不删除元素尾部的内容?

转载 作者:太空宇宙 更新时间:2023-11-03 18:04:55 24 4
gpt4 key购买 nike

我正在尝试删除 xml 文件中的节点。我已经设法做到这一点,但是当脚本运行时,它似乎采用了属于它后面的父元素的属性。

这是代码:

for i, pid in enumerate(root.findall(".//p")):
for cont in pid.findall('membercontribution'):
for col in cont.findall('col'):
cont.remove(col)


tree.write('fofo.xml')

这个:

<p id="S6CV0001P0-00507"><member>The Minister for Overseas Development (Mr. Neil Marten)        
</member><membercontribution>: a policy
<col>16</col>
foobar barforb </membercontribution></p>

变成这样:

<p id="S6CV0001P0-00507"><member>The Minister for Overseas Development (Mr. Neil Marten)    
</member><membercontribution>: a policy </membercontribution></p>

我该如何编码才能保留后面的“foobar barforb”部分?

最佳答案

这里无意中删除的不是属性,而是元素 tail 的内容。 .

tail 属性是 ElementTree API 的一个特性。它是紧跟在元素的结束标记之后、任何其他标记之前的文本。当您删除一个元素(在本例中为 col)时,您也会删除它的尾部。

我找到的最清楚的解释是:http://infohost.nmt.edu/tcc/help/pubs/pylxml/web/etree-view.html .

<小时/>

要获得所需的输出,您需要保留对已删除的 col 元素尾部的引用,并将其附加到父元素的文本中。一个完整的例子:

from xml.etree import ElementTree as ET

XML = """
<root>
<p id="S6CV0001P0-00507"><member>The Minister for Overseas Development (Mr. Neil Marten)
</member><membercontribution>: a policy
<col>16</col>
foobar barforb </membercontribution></p>
</root>
"""

root = ET.fromstring(XML)

for pid in root.findall(".//p"):
for cont in pid.findall('membercontribution'):
for col in cont.findall('col'):
col_tail = col.tail.strip() # Get the tail of "col"
cont.remove(col) # Remove "col"
cont.text = cont.text.strip() + " " # Replace trailing whitespace with single space
cont.text = cont.text + col_tail # Add the tail to "membercontribution"

print ET.tostring(root)

输出:

<root>
<p id="S6CV0001P0-00507"><member>The Minister for Overseas Development (Mr. Neil Marten)
</member><membercontribution>: a policy foobar barforb</membercontribution></p>
</root>

关于python - 如何删除 XML 元素而不删除元素尾部的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27077270/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com