如何使用xml.etree.ElementTree编写XML声明 [英] How to write XML declaration using xml.etree.ElementTree
问题描述
我正在使用 <$ c $在Python中生成XML文档c> ElementTree ,但是 tostring
函数不包含转换为纯文本时的XML声明。
I am generating an XML document in Python using an ElementTree
, but the tostring
function doesn't include an XML declaration when converting to plaintext.
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声明:
I need my string to include the following XML declaration:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
但是,似乎没有任何记录的方式。
However, there does not seem to be any documented way of doing this.
是否存在用于在 ElementTree
中呈现XML声明的适当方法?
Is there a proper method for rendering the XML declaration in an ElementTree
?
推荐答案
我很惊讶地发现 ElementTree.tostring()
似乎没有办法。但是,您可以使用 ElementTree.ElementTree.write()
将XML文档写入伪文件:
I am surprised to find that there doesn't seem to be a way with ElementTree.tostring()
. You can however use ElementTree.ElementTree.write()
to write your XML document to a fake file:
from io import BytesIO
from xml.etree import ElementTree as ET
document = ET.Element('outer')
node = ET.SubElement(document, 'inner')
et = ET.ElementTree(document)
f = BytesIO()
et.write(f, encoding='utf-8', xml_declaration=True)
print(f.getvalue()) # your XML file, encoded as UTF-8
请参阅此问题。即使那样,我认为如果不自己编写,就无法获得独立属性。
See this question. Even then, I don't think you can get your 'standalone' attribute without writing prepending it yourself.
这篇关于如何使用xml.etree.ElementTree编写XML声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!