关于python:如何使用xml.etree.ElementTree编写XML声明

How to write XML declaration using xml.etree.ElementTree

我正在使用ElementTree在python中生成一个XML文档,但是tostring函数在转换为纯文本时不包含XML声明。

1
2
3
4
5
6
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声明:

1
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>

然而,似乎没有任何记录在案的方法来做到这一点。

ElementTree中是否有适当的呈现XML声明的方法?


它是"to find I AM T,似乎是一个不到的方式与ElementTree.tostring()。但是你可以使用的XML文件的读写ElementTree.ElementTree.write()今天你到了一个假文件: </P >

1
2
3
4
5
6
7
8
9
10
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

它的这一问题。即使那,我不认为你能让你的"独立的属性不prepending IT yourself写作。 </P >


我会用lxml(http:/ / / api.html lxml.de)。 </P >

然后你可以: </P >

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


如果你的encoding='utf8'include,你会得到一个XML文档的标题: </P >

xml.etree.ElementTree.tostring writes a XML encoding declaration with encoding='utf8'

(Python Python代码样本厂(2和3): </P >

1
2
3
4
5
6
7
8
9
10
11
12
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 </P >

1
2
3
4
5
6
7
$ python2 example.py
without:
<xml><test>123</test></xml>

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

你将注意与Python 3字节的文字显示的bprefix returned(正是用Python的类(2): </P >

1
2
3
4
5
6
7
$ python3 example.py
without:
b'<xml><test>123</test></xml>'

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


这个问题太encounter I,售后服务部digging一些代码,我发现下面的代码的功能是定义ElementTree.writesnippet </P >

1
2
3
4
5
6
7
8
9
10
11
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'?>
"
%
     encoding)
    self._write(file, self._root, encoding, {})

所以如果你的答案是,那些对你的标题写的XML文件,比其他的参数集encodingutf-8us-ascii,例如utf-8 </P >


小包装的工作实例与ElementTreeusage: </P >

1
2
3
4
5
6
7
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)

的输出是: </P >

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

另一选择是很简单的desired头连接到本院对XML字符串类: </P >

1
2
3
4
5
xml = (bytes('<?xml version="1.0" encoding="UTF-8"?>
'
, encoding='utf-8') + ET.tostring(root))
xml = xml.decode('utf-8')
with open('invoice.xml', 'w+') as f:
    f.write(xml)


包括"独立"的申报

我没发现任何的替代方法在文献standaloneadding的论点,所以我把它的功能来适应ET.tosting为一的说法。 </P >

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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+"
"
)
     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)

本厂是如果你想打印。当我得到一双误差对发送它到一个文件………………… </P >

1
2
3
4
5
6
7
8
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=" ")

我会使用: </P >

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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))