简体   繁体   English

通过python更改多个文件的xml属性的名称

[英]Change name of xml attribute for multiple files via python

I would like to change the name of an attribute on an xml element in multiple files. 我想在多个文件中更改xml元素上的属性名称。 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. 我有1000个这样的文件,因此那些属性名称的位置不是绝对的。

My file is available at [XML FILE][1]. 我的文件位于[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]. 但是不确定此名称“带有错误条的多集柱形图”将始终位于位置[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. 我必须删除到源xml文件的链接,因为此文件是我的研究项目的一部分。

I am assuming that the structure of your xml file will be same as 我假设您的xml文件的结构将与

<?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: 您可以选择标签attribute并为该标签设置属性,如下所示:

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 然后将更改写入xml文件

tree.write("file_name")

Have a good reading here about xml and python 在这里有关于xml和python的良好阅读

A bit different from bhansa solution. 与bhansa解决方案略有不同。 I need some if else clause to check the names and then replace the name for some conditions. 我需要一些if else子句来检查名称,然后在某些情况下替换名称。

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

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

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