1

I'm trying to update an attribute on a child, then write that updated element to the document. I'm running into this error: 'AttributeError: Element instance has no attribute 'getiterator' '

I made this after piecing together a bunch of tutorials and resources, so let me know if anything else stands out (not too sure what I'm doing). Thanks!

Here's what I have so far:

Inside the XML doc:

<?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>

Write XML code:

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()

1 Answer 1

1

Use the xml.etree.ElementTree to search and set the element's attribute:

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)

Here we are using a simple 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.

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

1 Comment

It worked! Great explaination too, thanks for taking the time :D

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.