Python和XML:更新一个属性和写文件的问题

Python and XML: Update an attribute and write file problems

我正在尝试更新子项的属性,然后将该更新后的元素写入文档。我 运行 遇到了这个错误:'AttributeError: Element instance has no attribute 'getiterator' '

这是我在拼凑了一堆教程和资源之后制作的,所以如果有什么特别突出的地方请告诉我(不太确定我在做什么)。谢谢!

这是我目前的情况:

在 XML 文档中:

<?xml version="1.0" ?>
<notes>
    <prepData a_assetType="Geometry" b_assetSel="[u'pPyramid1', u'pTorus1']"/>
    <prepData a_assetType="Rig" b_assetSel="[u'pPyramid1']"/>
    <prepData a_assetType="Controls" b_assetSel="[u'pPyramid1']"/>
</notes>

编写XML代码:

xml_file_path = "{0}/{1}_prepData.xml".format( info_dir, asset_type )
doc = ET.parse( xml_file_path )
dom = parse( xml_file_path )
root = doc.getroot()

nodes = dom.getElementsByTagName( 'prepData' )

match = []
for node in nodes:
    if node.attributes['a_assetType'].value == asset_type:
        match.append( node )

for node in match:
    node.setAttribute( "b_assetSel", str(asset_sel) )


out = ET.tostring( node )
dom = minidom.parseString( out )
xml_file = open("{0}/{1}_prepData.xml".format( info_dir, asset_name ), "w")
xml_file.write( dom.toprettyxml() )
xml_file.close()

使用xml.etree.ElementTree搜索并设置元素的属性:

import xml.etree.ElementTree as ET

doc = ET.parse(xml_file_path)
root = doc.getroot()

for elm in root.findall(".//prepData[@a_assetType='%s']" % asset_type):
    elm.attrib["b_assetSel"] = str(asset_sel)

out = ET.tostring(root)
print(out)

这里我们使用的是简单的XPath expression to find all prepData elements having the desired a_assetType attribute value. For each element found, we set the b_assetSel attribute value via the .attrib