在python和lxml中生成xml [英] Generating xml in python and lxml

查看:300
本文介绍了在python和lxml中生成xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有来自sql的xml,并且我想通过python 2.7和lxml进行同样的操作

I have this xml from sql, and I want to do the same by python 2.7 and 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()

您知道如何添加其余属性吗?

Do you know how to add rest of attributes?

推荐答案

请注意,这也将打印BOM

Note this also prints the 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和lxml中生成xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆