在elementtree中查找和替换文本

时间:2013-07-29 08:30:10

标签: python elementtree

我是编程和python的新手。我试图找到并替换xml文件中的文本。这是我的xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!--Arbortext, Inc., 1988-2008, v.4002-->
<!DOCTYPE doc PUBLIC "-//MYCOMPANY//DTD XSEIF 1/FAD 110 05 R5//EN"
 "XSEIF_R5.dtd">
<doc version="XSEIF R5"
xmlns="urn:x-mycompany:r2:reg-doc:1551-fad.110.05:en:*">
<meta-data></meta-data>
<front></front> 
<body>
<chl1><title xml:id="id_881i">Installation</title>
<p>To install SDK, perform the tasks mentioned in the following
table.</p>
<p><input>ln -s /sim/<var>user_id</var>/.VirtualBox $home/.VirtualBox</input
></p>
</chl1>
</body>
</doc>
 <?Pub *0000021917 0?>

我需要用“Xen”替换“虚拟盒子”的所有条目。为此,我尝试了Elementtree。但我不知道如何替换和写回文件。这是我的尝试。

import xml.etree.ElementTree as ET
tree=ET.parse('C:/My_location/1_1531-CRA 119     1364_2.xml')
doc=tree.getroot()
iterator=doc.getiterator()
 for body in iterator:
    old_text=body.replace("Virtualbox", "Xen")

这些文本可以在body下的许多子标签中找到。我得到了删除子元素并附加一个新元素的方法,但是没有只替换文本。

2 个答案:

答案 0 :(得分:1)

替换文字,尾部属性。

import lxml.etree as ET

with open('1.xml', 'rb+') as f:
    tree = ET.parse(f)
    root = tree.getroot()
    for elem in root.getiterator():
        if elem.text:
            elem.text = elem.text.replace('VirtualBox', 'Xen')
        if elem.tail:
            elem.tail = elem.tail.replace('VirtualBox', 'Xen')

    f.seek(0)
    f.write(ET.tostring(tree, encoding='UTF-8', xml_declaration=True))
    f.truncate()

答案 1 :(得分:0)

可能最简单的方法是:

ifile = open('input_file','r')
ofile = open('output_file','w')
for line in ifile.readlines():
  ofile.write(line.replace('VirtualBox','Xen'))
ifile.close()
ofile.close()
相关问题