Home > Net >  How can I change the subchild value/text with python for XML file
How can I change the subchild value/text with python for XML file

Time:08-31

My xml code looks like this:

    <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.

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.

CodePudding user response:

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) 
  • Related