我试图删除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”部分?在
这里无意中删除的不是属性,而是元素的^{} 的内容。在
tail
属性是elementtreeapi的一个特性。它是紧跟在元素结束标记之后和任何其他标记之前的文本。当您移除一个元素(在本例中是col
)时,您也会移除其尾部。在我发现的最清楚的解释是:http://infohost.nmt.edu/tcc/help/pubs/pylxml/web/etree-view.html。在
要获得所需的输出,需要保留对已删除的
col
元素尾部的引用,并将其附加到父元素的文本中。一个完整的例子:输出:
^{pr2}$相关问题 更多 >
编程相关推荐