Python - 在没有根的情况下向 xml 添加新元素?

Python - add new elements to xml without a root?

我需要制作具有如下结构的 xml:

<?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>
...

是否可以这样创建? 由于没有定义根元素(每个元素都是“根”),我应该逐个元素地创建..

任何帮助都会有所帮助, 谢谢!

<?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>

这不是 XML 文档XML specification

A data object is an XML document if it is well-formed, as defined in this specification

并且您的示例违反了以下规则

There is exactly one element, called the root, or document element, no part of which appears in the content of any other element.

for each non-root element C in the document, there is one other element P in the document such that C is in the content of P, but is not in the content of any other element that is in the content of P.

见下文。

假设您的数据在 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)

输出

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