要输出 xml 声明<?xml version="1.0" encoding="utf-8"?>
,请使用lxml.etree.tostring
withxml_declaration=True, encoding='utf-8'
作为参数。
nsmap
要添加命名空间元素,请在创建元素时传递参数。
>>> import lxml.etree
>>>
>>> nsmap = {
... None: "urn:iso:std:iso:2013:008.001.02",
... 'xsi': "http://www.w3.org/2001/XMLSchema-instance",
... }
>>> root = lxml.etree.Element('Document', nsmap=nsmap)
>>> lxml.etree.SubElement(root, 'page1')
<Element page1 at 0x2ad8af8>
>>> print lxml.etree.tostring(root, xml_declaration=True, encoding='utf-8', pretty_print=True)
<?xml version='1.0' encoding='utf-8'?>
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:iso:std:iso:2013:008.001.02">
<page1/>
</Document>
>>>