在python和lxml中生成xml

我有来自sql的这个xml,我想通过python 2.7和lxml做同样的事情

<?xml version="1.0" encoding="utf-16"?>
<results>
  <Country name="Germany" Code="DE" Storage="Basic" Status="Fresh" Type="Photo" />
</results>

我现在有:

from lxml import etree

# create XML 
results= etree.Element('results')

country= etree.Element('country')
country.text = 'Germany'
root.append(country)



filename = "xmltestthing.xml"
FILE = open(filename,"w")
FILE.writelines(etree.tostring(root, pretty_print=True))
FILE.close()

你知道如何添加其他属性吗?

解决方法:

请注意,这也会打印BOM

>>> from lxml.etree import tostring
>>> from lxml.builder import E
>>> print tostring(
             E.results(
                 E.Country(name='Germany',
                           Code='DE',
                           Storage='Basic',
                           Status='Fresh',
                           Type='Photo')
             ), pretty_print=True, xml_declaration=True, encoding='UTF-16')

��<?xml version='1.0' encoding='UTF-16'?>
<results>
  <Country Status="Fresh" Type="Photo" Code="DE" Storage="Basic" name="Germany"/>
</results>
上一篇:python – 在Centos 7上安装lxml – 错误:命令’gcc’失败,退出状态为4


下一篇:Python XML删除了一些元素及其子元素,但保留了特定元素及其子元素