如何在不删除元素尾部内容的情况下删除XML元素?

2024-09-17 18:26:11 发布

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

我试图删除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')

这个:

^{pr2}$

变成这样:

^{3}$

如何编写代码,以便保留后面的“foobar barforb”部分?在


Tags: 文件代码in脚本元素for属性节点
1条回答
网友
1楼 · 发布于 2024-09-17 18:26:11

这里无意中删除的不是属性,而是元素的^{}的内容。在

tail属性是elementtreeapi的一个特性。它是紧跟在元素结束标记之后和任何其他标记之前的文本。当您移除一个元素(在本例中是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)

输出:

^{pr2}$

相关问题 更多 >