python - 在python和lxml中生成xml

标签 python xml lxml

我有这个来自 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 - 在python和lxml中生成xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4469983/

相关文章:

python - Anaconda 与 IBM Watson Studio

python - 噪声数据中的梯度,python

java - 发送 SOAP 消息

xml - XSD 验证 xs :date and xs:dateTime 的错误格式

python - tostring 中的 pretty_print 选项在 lxml 中不起作用

python - PuLP 错误+self.path

python - 尝试写入行时出现“FieldMissingError”

xml - eclipse 3.5 : How to get file name from Editor?

python - 仅列出一种类别 Python xml

python lxml 添加未使用的命名空间