使用Python将仅XML声明写入文件

3

我将在Python中循环遍历字符串列表来编写多个XML文件。

假设我有:

from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring

parent = Element('parent')
child = SubElement(parent, 'child')
f = open('file.xml', 'w')
document = ElementTree(parent)
l = ['a', 'b', 'c']
for ch in l:
    child.text = ch
    document.write(f, encoding='utf-8', xml_declaration=True)

输出结果:
<?xml version='1.0' encoding='utf-8'?>
<parent><child>a</child></parent><?xml version='1.0' encoding='utf-8'?>
<parent><child>b</child></parent><?xml version='1.0' encoding='utf-8'?>
<parent><child>c</child></parent>

期望的输出:

<?xml version='1.0' encoding='utf-8'?>
<parent>
<child>a</child>
<child>b</child>
<child>c</child>
</parent>

我只希望在文件顶部出现一次xml声明。可能应该在循环之前将声明写入文件,但是当我尝试这样做时,会得到空元素。我不想这样做:
f.write('<?xml version='1.0' encoding='utf-8'?>')

如何将xml声明写入文件? 编辑:期望输出
3个回答

6

在写文件之前,您需要将SubItems添加到树中。在您的代码中,您覆盖了同一个元素并在循环的每次迭代中写入整个XML文档。

另外,您的XML语法缺少顶级“root”元素才能有效。

from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring

root = Element('root')

l = ['a', 'b', 'c']
for ch in l:
    parent = SubElement(root,'parent')
    child = SubElement(parent, 'child')
    child.text = ch

document = ElementTree(root)
document.write('file.xml', encoding='utf-8', xml_declaration=True)

输出结果将是:

<?xml version='1.0' encoding='utf-8'?>
<root>
  <parent><child>a</child></parent>
  <parent><child>b</child></parent>
  <parent><child>c</child></parent>
</root> 

1

我不熟悉Python的XML库,但是让我们退一步。如果你按照你想要的方式操作,你的输出将不是有效的XML。XML必须有一个且仅有一个根元素

因此,你可以有:

<?xml version='1.0' encoding='utf-8'?>
<uberparent>
<parent><child>a</child></parent>
<parent><child>b</child></parent>
<parent><child>c</child></parent>
</uberparent>

假设您正在创建一个Google网站地图,例如:他们的架构 表示根元素是 "urlset"。

0

这在技术上是可行的,只需在xml_declaration上设置一个bool()标志:

parent = Element('parent')
child = SubElement(parent, 'child')
f = open('file.xml', 'w')
document = ElementTree(parent)
l = ['a', 'b', 'c']
# use enumerate to have (index, element) pair, started from 0
for i, ch in enumerate(l):
    child.text = ch
    # Start index=0, since bool(0) is Fale, and bool(1..n) is True
    # the flag will be offset
    document.write(f, encoding='utf-8', xml_declaration=bool(not i))
f.close()

更新:

由于OP已经意识到所需的输出在语法上是不正确的,并更改了要求,这里是处理xml的常规方法:

from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring

parent = Element('parent')
f = open('file.xml', 'w')
document = ElementTree(parent)
l = ['a', 'b', 'c']
for ch in l:
    child = SubElement(parent, 'child')
    child.text = ch
document.write(f, encoding='utf-8', xml_declaration=True)
f.close()

虽然作为一个附注,就像@Amirshk提到的那样,这不是一个有效的XML语法。 - Anzel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接