How to set attributes for an XML element using Python?

I am using ElementTree to create an XML file.

When I try to set an element attribute using ET.SubElement().__setattr__() , I get the AttributeError: __setattr__ error message.

 import xml.etree.cElementTree as ET summary = open(Summary.xml, 'w') root = ET.Element('Summary') ET.SubElement(root, 'TextSummary') ET.SubElement(root,'TextSummary').__setattr__('Status','Completed') # Error occurs here tree = ET.ElementTree(root) tree.write(summary) summary.close() 

After executing the code, my XML should look like this:

 <Summary> <TextSummary Status = 'Completed'/> </Summary> 

How to add attributes to an XML element using Python using xml.etree.cElementTree ?

+4
source share
2 answers

You must do:

 ET.SubElement(root,'TextSummary').set('Status','Completed') 

The Etree documentation shows usage .

+11
source

You can specify SubElement attributes at creation time using keyword arguments:

 root = ET.Element('Summary') ET.SubElement(root, 'TextSummary', Status='Completed') 

Alternatively, you can use .set to add an attribute to an element after creation.

 root = ET.Element('Summary') sub = ET.SubElement(root, 'TextSummary') sub.set('Status', 'Completed') 

Python example:

 import xml.etree.ElementTree as ET root = ET.Element('Summary') ET.SubElement(root, 'TextSummary', Status='Completed') print(ET.tostring(root).decode()) 

XML Output:

 <Summary> <TextSummary Status = "Completed"/> </Summary> 

Explanation:

Constructors for Element and SubElement include **extra , which accepts attributes as keyword arguments.

 xml.etree.ElementTree.Element(tag, attrib={}, **extra) xml.etree.ElementTree.SubElement(parent, tag, attrib={}, **extra) 

This allows you to add an arbitrary number of attributes.

 root = ET.Element('Summary', Date='2018/07/02', Timestamp='11:44am') # <Summary Date = "2018/07/02" Timestamp = "11:44am"> 

You can also use .set to add attributes to a pre-existing item. However, this can only add one item at a time. ( Offered by Thomas Orozco ).

 root = ET.Element('Summary') root.set('Date', '2018/07/02') root.set('Timestamp', '11:44am') # <Summary Date = "2018/07/02" Timestamp = "11:44am"> 
0
source

Source: https://habr.com/ru/post/1502132/


All Articles