pythonxmlparsingelementtreeminidom

Python - add new elements to xml without a root?


I need to make xml which has structure like this:

<?xml version='1.0' encoding='utf-8'?>
<tag1 atrib1='bla' atrib1='bla' atrib1='bla' atrib1='bla'>
<tag2 atrib = 'something'>
<tag3 atrib = 'something'>
<tag4 atrib = '..'>
<tag5 atrib = 'important'><div><h1>ContentFrom **OldXml.xml** </h1></div>
...

is it possible to create it like this? Since there is no root element defined (every element is the "root"), and I should just create element by element..

Any assistance would help, Thanks!


Solution

  • See below.

    Assuming your data is in data

    import xml.etree.ElementTree as ET
    
    
    data = [[1],['x','y'],['k',12,'zz']]
    
    root = ET.Element("root")
    for i,entry in enumerate(data):
      ET.SubElement(root,f'tag{i}',attrib={f'p{y}':str(v) for y,v in enumerate(entry)})
    ET.dump(root)
    

    output

    <?xml version="1.0" encoding="UTF-8"?>
    <root>
       <tag0 p0="1" />
       <tag1 p0="x" p1="y" />
       <tag2 p0="k" p1="12" p2="zz" />
    </root>