我在Python中使用^{tostring
函数在转换为纯文本时不包含XML declaration。
from xml.etree.ElementTree import Element, tostring
document = Element('outer')
node = SubElement(document, 'inner')
node.NewValue = 1
print tostring(document) # Outputs "<outer><inner /></outer>"
我需要我的字符串包含以下XML声明:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
然而,似乎没有任何记录的方法来做到这一点。
是否有在ElementTree
中呈现XML声明的正确方法?
我很惊讶地发现,似乎没有办法处理
ElementTree.tostring()
。但是,您可以使用ElementTree.ElementTree.write()
将XML文档写入假文件:见this question。即使这样,我也不认为不自己编写预处理就可以获得“standalone”属性。
If you include the ^{}, you will get an XML header :
示例Python代码(适用于Python 2和3):
Python 2输出:
对于Python 3,您将注意到the ^{} prefix 表示返回字节文本(就像Python 2一样):
我会使用lxml(参见http://lxml.de/api.html)。
然后你可以:
相关问题 更多 >
编程相关推荐