0

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.

END NOTE

I had to remove the link to the source xml file because this file is part of my research project.

3
  • select the attribute name and then update it. Commented Jul 28, 2016 at 16:21
  • How can I do that? Commented Jul 28, 2016 at 16:28
  • Please select any of the answers below as answered and close this question. Commented Sep 29, 2017 at 10:49

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.