Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the arguments of ElementTree.SubElement used for?

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.

like image 417
tim tran Avatar asked Apr 02 '12 06:04

tim tran


People also ask

What is ElementTree?

ElementTree is an important Python library that allows you to parse and navigate an XML document. Using ElementTree breaks down the XML document in a tree structure that is easy to work with.

What does Etree parse do?

The parse() function is used to parse from files and file-like objects. As an example of such a file-like object, the following code uses the BytesIO class for reading from a string instead of an external file.

How do you parse an XML string in Python?

3.2 Parsing an XML String We use the ElementTree. fromstring() method to parse an XML string. The method returns root Element directly: a subtle difference compared with the ElementTree. parse() method which returns an ElementTree object.


1 Answers

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>
>>>
like image 86
circus Avatar answered Sep 25 '22 03:09

circus