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!
CodePudding user response:
<?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>
This is not XML document, XML specification
A data object is an XML document if it is well-formed, as defined in this specification
and your example break following rules
There is exactly one element, called the root, or document element, no part of which appears in the content of any other element.
and
for each non-root element
C
in the document, there is one other elementP
in the document such thatC
is in the content ofP
, but is not in the content of any other element that is in the content ofP
.
CodePudding user response:
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>