在elementtree中查找和替换文本 [英] Find and replacing text in elementtree

查看:268
本文介绍了在elementtree中查找和替换文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对编程和python很陌生。我正在尝试查找和替换xml文件中的文本。这是我的xml文件

i am very new to programming and python. I am trying to find and replace a text in an xml file. Here is my xml file

<?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替换 virtual box的所有条目。为此,我尝试了Elementtree。但是我不知道如何替换并写回文件。这是我的尝试。

I need to replace all entries of "virtual box" with "Xen". For this i tried Elementtree. But i dont know how to replace and write back to the file. Here is my try.

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")

正文下方的许多子标签中都有这些文本我得到了删除子元素并追加一个新元素的方法,但没有只替换文本。

The texts are available in many sub tags under body.I got the method to remove the subelement and append a new element, but didnt get to replace only the texts.

推荐答案

替换文本,尾部属性。

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()

这篇关于在elementtree中查找和替换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆