简体   繁体   English

如何使用 XML 文件的 python 更改子值/文本

[英]How can I change the subchild value/text with python for XML file

My xml code looks like this:我的 xml 代码如下所示:

    <object>
        <name>ENERGY-TAG</name>
        <pose>Unspecified</pose>
        <truncated>1</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>397</xmin>
            <ymin>470</ymin>
            <xmax>1500</xmax>
            <ymax>1816</ymax>
        </bndbox>
    </object>
</annotation>

And I want to change "ENERGY-TAG" into "ERJ" by using xml.etree and overwrite onto same file.我想通过使用 xml.etree 将“ENERGY-TAG”更改为“ERJ”并覆盖到同一个文件上。

My code is:我的代码是:

root=ET.parse("C:/Users/PC/Desktop/185.xml")
objects=root.findall(".//object")
object_name = []

for o in objects:
    # print(o.find("name").text)
    if o.find("name").text == "ENERGY-TAG":
       o.text = "ERJ"

Thanks in advance.提前致谢。

You are almost there - you just need to change and write the file properly:您快到了 - 您只需要正确更改和写入文件:

tree= ET.parse('C:/Users/PC/Desktop/185.xml')
root = tree.getroot()

objects=root.findall(".//object")

for o in objects:
    if o.find("name").text == "ENERGY-TAG":
        o.find("name").text = "ERJ"

#Note that you write() tree, not root
tree.write("C:/Users/PC/Desktop/185.xml", encoding="utf-8", xml_declaration=True) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM