I would like to change the name of an attribute on an xml element in multiple files. These files are an output from an image annotation tool. I have 1000 of such files, thus the position of those attribute name is not absolute.
My file is available at [XML FILE][1].
Here I would like to change
<attribute dynamic="false" name="Multiset Column Chart with Error Bars " type="http://lamp.cfar.umd.edu/viperdata#bbox"/>
TO
<attribute dynamic="false" name="Column Chart " type="http://lamp.cfar.umd.edu/viperdata#bbox"/>
and
<attribute name="Multiset Column Chart with Error Bars "/>
TO
<attribute name="Column Chart "/>
So far I can access the element in the first code snipped as
root=xmldoc.getroot()
print(root[0][0][11].attrib)
but it is not certain that this name "Multiset Column Chart with Error Bars " will always be at position [0][0][11].
So, I am not sure how can I access those specific names and can change the value for the name as I showed above.
Any assistance will be appreciated.
I had to remove the link to the source xml file because this file is part of my research project.
I am assuming that the structure of your xml file will be same as
<?xml version="1.0" encoding="UTF-8"?>
<viper xmlns="http://lamp.cfar.umd.edu/viper#" xmlns:data="http://lamp.cfar.umd.edu/viperdata#">
<config>
<descriptor name="Desc0" type="OBJECT">
<attribute dynamic="false" name="Reflexive Bar Chart " type="http://lamp.cfar.umd.edu/viperdata#bbox"/>
and so on.
you can select the tag attribute
and set the attribute for that tag like this:
import xml.etree.ElementTree as ET
tree = ET.parse('contents.xml').getroot()
print tree.tag, tree.text
for child in tree[0][0]:
print child.set("name","bhansa")
print child.attrib #just to check whether changed or not
then write the changes in xml file
tree.write("file_name")
Have a good reading here about xml and python
A bit different from bhansa solution. I need some if else clause to check the names and then replace the name for some conditions.
root=xmldoc.getroot()
#print(root[0][0])
for child in root[0][0]:
if(child.get('name') == 'Coulmn Chart with Error Bars '):
child.set("name","Column Chart")
print (child.attrib) #just to check whether changed or not
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.