ElementTree attrib是空的

时间:2015-05-21 08:14:31

标签: python xml parsing python-3.x

我有XML文档。

<idmclient>
    <version build="" major="1" minor="1" sprint="15" />  
</idmclient>

和python代码

  import xml.etree.ElementTree as ET
from xml.etree.ElementTree import parse, Element, SubElement, ElementTree
import sys
file = "C://inetpub//idmclient//version.xml";
tree = parse(file)
elem = tree.getroot()
version = SubElement(elem, "version")
print (version.attrib)

它的打印{}。但我有4个属性。之后,我想在构建任何数字并保存,但现在,当我写和保存它看起来像这样

  <idmclient>
    <version build="" major="1" minor="1" sprint="15" />
<version build="666" /></idmclient>    

感谢。

1 个答案:

答案 0 :(得分:1)

使用find()代替按名称获取元素。然后,您可以使用set()更新build属性值,如下所示:

.....
version = elem.find('version')
version.set('build', '666')

print(version.attrib)
# output :
# {'major': '1', 'sprint': '15', 'minor': '1', 'build': '666'}