2

我正在使用 lxml 写出一个 cXML 文件,但我不知道如何让它写出开头<?xml version="1.0" encoding="UTF-8"?>以及后面的 doctype。当我开始这个时,我直接从文档本身开始,第一个元素是cXML timestamp="2015-02-01'T'12:00:00Z">'等等。现在我意识到由于没有开始标签和 doctype 定义,我可能会遇到解析错误,但我不知道如何让 lxml 如何写出这些错误。

4

1 回答 1

3

您可以将它们作为参数传递给tostring()方法。一个例子:

from lxml import etree

root = etree.Element('root')
etree.SubElement(root, 'child1')
etree.SubElement(root, 'child2')

print etree.tostring(root, encoding='UTF-8', xml_declaration=True, doctype='''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">''')

这会产生:

<?xml version='1.0' encoding='UTF-8'?>                                                                           
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"                                                                                                                                                                                                                       
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">                                                                                                                                                                                                                   
<root><child1/><child2/></root>
于 2015-02-11T10:48:49.570 回答