What are the arguments of ElementTree.SubElement used for?

tim tran picture tim tran · Apr 2, 2012 · Viewed 22.5k times · Source

I have looked at the documentation here:

http://docs.python.org/dev/library/xml.etree.elementtree.html#xml.etree.ElementTree.SubElement

The parent and tag argument seems clear enough, but what format do I put the attribute name and value in? I couldn't find any previous example. What format is the extra** argument?

I receive and error for trying to call the SubElement itself, saying that it is not defined. Thank you.

Answer

circus picture circus · Apr 2, 2012

SubElement is a function of ElementTree (not Element) which allows to create child objects for an Element.

  • attrib takes a dictionary containing the attributes of the element you want to create.

  • **extra is used for additional keyword arguments, those will be added as attributes to the Element.

Example:

>>> import xml.etree.ElementTree as ET
>>>
>>> parent = ET.Element("parent")
>>>
>>> myattributes = {"size": "small", "gender": "unknown"}
>>> child = ET.SubElement(parent, "child", attrib=myattributes, age="10" )
>>>
>>> ET.dump(parent)
<parent><child age="10" gender="unknown" size="small" /></parent>
>>>