What are the arguments of ElementTree.SubElement used for?
Asked Answered
H

2

11

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.

Hardesty answered 2/4, 2012 at 6:1 Comment(0)
M
5

If you look further down on the same page you linked to where it deals with class xml.etree.ElementTree.Element(tag, attrib={}, **extra) it tells you how any of the extra arguments work, that is by e.g.:

from etree import ElementTree as ET
a = ET.Element('root-node', tag='This is an extra that sets a tag')
b = ET.SubElement(a, 'nested-node 1')
c = ET.SubElement(a, 'nested-node 2')
d = ET.SubElement(c, 'innermost node')
ET.dump(a)

This also shows you how subelement works, you simply tell it which element (can be a subelsement) that you want to attach it to. For the future, supply some code too so it's easier to see what you're doing/want.

Murton answered 2/4, 2012 at 6:37 Comment(0)
W
25

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>
>>>
Weis answered 2/4, 2012 at 6:58 Comment(1)
So essentially attrib and **extra both add attributes, but they accept different data types.Coen
M
5

If you look further down on the same page you linked to where it deals with class xml.etree.ElementTree.Element(tag, attrib={}, **extra) it tells you how any of the extra arguments work, that is by e.g.:

from etree import ElementTree as ET
a = ET.Element('root-node', tag='This is an extra that sets a tag')
b = ET.SubElement(a, 'nested-node 1')
c = ET.SubElement(a, 'nested-node 2')
d = ET.SubElement(c, 'innermost node')
ET.dump(a)

This also shows you how subelement works, you simply tell it which element (can be a subelsement) that you want to attach it to. For the future, supply some code too so it's easier to see what you're doing/want.

Murton answered 2/4, 2012 at 6:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.