如何使用xml.etree.ElementTree编写XML声明

问题描述 投票:44回答:9

我使用的是ElementTree Python中生成一个XML文件,但转换为纯文本时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声明适当的方法?

python xml elementtree
9个回答
81
投票

我很惊讶地发现,似乎没有要与ElementTree.tostring()的方式。但是,您可以使用ElementTree.ElementTree.write()到XML文档写入文件假货:

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

this question。即使是这样,我不认为你可以得到你的“独立”属性,而无需编写自己前面加上。


21
投票

我会用LXML(见http://lxml.de/api.html)。

那么你也能:

from lxml import etree
document = etree.Element('outer')
node = etree.SubElement(document, 'inner')
print(etree.tostring(document, xml_declaration=True))

14
投票

If you include the encoding='utf8', you will get an XML header

xml.etree.ElementTree.tostring写入XML编码声明用编码=“UTF8”

示例Python代码(与Python 2和3的工作原理):

import xml.etree.ElementTree as ElementTree

tree = ElementTree.ElementTree(
    ElementTree.fromstring('<xml><test>123</test></xml>')
)
root = tree.getroot()

print('without:')
print(ElementTree.tostring(root, method='xml'))
print('')
print('with:')
print(ElementTree.tostring(root, encoding='utf8', method='xml'))

Python 2中的输出:

$ python2 example.py
without:
<xml><test>123</test></xml>

with:
<?xml version='1.0' encoding='utf8'?>
<xml><test>123</test></xml>

使用Python 3,你会注意到the b prefix指示返回(就像使用Python 2)字节的文字:

$ python3 example.py
without:
b'<xml><test>123</test></xml>'

with:
b"<?xml version='1.0' encoding='utf8'?>\n<xml><test>123</test></xml>"

3
投票

我最近遇到此问题,代码的一些挖后,我发现下面的代码片段是功能ElementTree.write的定义

def write(self, file, encoding="us-ascii"):
    assert self._root is not None
    if not hasattr(file, "write"):
        file = open(file, "wb")
    if not encoding:
        encoding = "us-ascii"
    elif encoding != "utf-8" and encoding != "us-ascii":
        file.write("<?xml version='1.0' encoding='%s'?>\n" % 
     encoding)
    self._write(file, self._root, encoding, {})

因此,答案是,如果需要XML头写信给你的文件,设置比encodingutf-8,如其他us-ascii说法UTF-8


2
投票

最小工作示例与ElementTree包用法:

import xml.etree.ElementTree as ET

document = ET.Element('outer')
node = ET.SubElement(document, 'inner')
node.text = '1'
res = ET.tostring(document, encoding='utf8', method='xml').decode()
print(res)

输出是:

<?xml version='1.0' encoding='utf8'?>
<outer><inner>1</inner></outer>

0
投票

我会用ET

try:
    from lxml import etree
    print("running with lxml.etree")
except ImportError:
    try:
        # Python 2.5
        import xml.etree.cElementTree as etree
        print("running with cElementTree on Python 2.5+")
    except ImportError:
        try:
            # Python 2.5
            import xml.etree.ElementTree as etree
            print("running with ElementTree on Python 2.5+")
        except ImportError:
            try:
                # normal cElementTree install
                import cElementTree as etree
                print("running with cElementTree")
            except ImportError:
               try:
                   # normal ElementTree install
                   import elementtree.ElementTree as etree
                   print("running with ElementTree")
               except ImportError:
                   print("Failed to import ElementTree from any known place")

document = etree.Element('outer')
node = etree.SubElement(document, 'inner')
print(etree.tostring(document, encoding='UTF-8', xml_declaration=True))

0
投票

这工作,如果你只想打印。得到一个错误,当我尝试把它发送到一个文件...

import xml.dom.minidom as minidom
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element, SubElement, Comment, tostring

def prettify(elem):
    rough_string = ET.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="  ")

0
投票

Including 'standalone' in the declaration

我没有发现的文档中添加standalone论点的替代,所以我适应了ET.tosting功能,把它作为一个参数。

from xml.etree import ElementTree as ET

# Sample
document = ET.Element('outer')
node = ET.SubElement(document, 'inner')
et = ET.ElementTree(document)

 # Function that you need   
 def tostring(element, declaration, encoding=None, method=None,):
     class dummy:
         pass
     data = []
     data.append(declaration+"\n")
     file = dummy()
     file.write = data.append
     ET.ElementTree(element).write(file, encoding, method=method)
     return "".join(data)
# Working example
xdec = """<?xml version="1.0" encoding="UTF-8" standalone="no" ?>"""    
xml = tostring(document, encoding='utf-8', declaration=xdec)

0
投票

另一个非常简单的选择是所需的标题并置到这样的XML字符串:

xml = (bytes('<?xml version="1.0" encoding="UTF-8"?>\n', encoding='utf-8') + ET.tostring(root))
xml = xml.decode('utf-8')
with open('invoice.xml', 'w+') as f:
    f.write(xml)
© www.soinside.com 2019 - 2024. All rights reserved.