gpt4 book ai didi

python - 在 elementtree 中查找并替换文本

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

我对编程和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?>

我需要将“virtual box”的所有条目替换为“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")

正文下的许多子标签中都提供了文本。我找到了删除子元素并附加新元素的方法,但无法仅替换文本。

最佳答案

替换文本、尾部属性。

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

关于python - 在 elementtree 中查找并替换文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17919305/

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