How do I set attributes for an XML element with Python?

后端 未结 3 1272
故里飘歌
故里飘歌 2020-12-30 08:55

I am using ElementTree to build an XML file.

When I try to set an element\'s attribute with ET.SubElement().__setattr__(), I get the error Attribu

3条回答
  •  爱一瞬间的悲伤
    2020-12-30 09:23

    You can specify attributes for an Element or SubElement during creation with keyword arguments.

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

    XML:

    
        
    
    

    Alternatively, you can use .set to add attributes to an existing element.

    import xml.etree.ElementTree as ET
    
    root = ET.Element('Summary')
    sub = ET.SubElement(root, 'TextSummary')
    sub.set('Status', 'Completed')
    

    XML:

    
        
    
    

    Technical Explanation:

    The 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')
    # 
    

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

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

    Full Example:

    import xml.etree.ElementTree as ET
    
    root = ET.Element('school', name='Willow Creek High')
    ET.SubElement(root, 'student', name='Jane Doe', grade='9')
    print(ET.tostring(root).decode())
    # 
    

提交回复
热议问题