【问题标题】:Find and replacing text in elementtree在 elementtree 中查找和替换文本
【发布时间】:2013-07-29 08:30:09
【问题描述】:

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

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

【问题讨论】:

    标签: python elementtree


    【解决方案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()
    

    【讨论】:

    • 您好,感谢您的回答。但它既不会抛出任何错误,也不会替换原始文件。我很困惑发生了什么。即使对于另一个脚本也发生了同样的情况。这里是。 import xml.etree.ElementTree as ET from xml.etree.ElementTree import Element tree=ET.parse('C:/Users/epeeham/Desktop/Official/SSR-SIM/Test/1_1531-CRA 119 1364_2.xml') doc =tree.getroot() elem=Element("approved-by") elem.attrib["approved"] = "yes" 我尝试将属性值从 no 设置为 yes。但它没有给我一个错误,也没有工作。是不是我的xml有问题?
    • @ShahulHameed,我更新了代码。更新后的代码使用外部库lxml
    【解决方案2】:

    可能最简单的方法是这样做:

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

    【讨论】:

    • 您好,感谢您的回答。我在 Elementtree 方式之前尝试过这种方式。但是我的 xml 文件被完全清除了。内容变为空。不知道你
    • 如果你有正确的权限读取输入文件和写入输出文件,它必须工作。 ifile 必须与 ofile 不同。
    猜你喜欢
    • 1970-01-01
    • 2020-07-29
    • 2015-12-19
    • 2013-05-26
    • 2019-07-30
    • 2019-10-16
    • 2011-08-20
    • 2011-11-24
    • 2021-10-25
    相关资源
    最近更新 更多