Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在lxml中编写xml文档的开头?_Python_Xml_Lxml_Cxml - Fatal编程技术网

Python 如何在lxml中编写xml文档的开头?

Python 如何在lxml中编写xml文档的开头?,python,xml,lxml,cxml,Python,Xml,Lxml,Cxml,我正在使用lxml编写一个cXML文件,但我不知道如何让它写出开头的以及后面的doctype。当我开始这篇文章时,我直接开始了文档本身,第一个元素是cXML timestamp=“2015-02-01'T'12:00:00Z”>”,以此类推。现在我意识到,由于没有开始标记和doctype定义,我可能会遇到解析错误,但我不知道如何获得lxml以及如何写出它们。您可以将它们作为参数传递给tostring()方法。例如: from lxml import etree root = etree.Ele

我正在使用lxml编写一个cXML文件,但我不知道如何让它写出开头的
以及后面的doctype。当我开始这篇文章时,我直接开始了文档本身,第一个元素是
cXML timestamp=“2015-02-01'T'12:00:00Z”>”
,以此类推。现在我意识到,由于没有开始标记和doctype定义,我可能会遇到解析错误,但我不知道如何获得lxml以及如何写出它们。

您可以将它们作为参数传递给
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">''')
从lxml导入etree
root=etree.Element('root')
etree.SubElement(根“child1”)
etree.SubElement(根“child2”)
打印etree.tostring(根,编码为UTF-8,xml_声明为True,doctype为“”)
这将产生:

<?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>

工作正常。为了将它写到文件中,我使用了以下命令:
treeStr=ET.tostring(topline,encoding=“UTF-8”,xml\u声明=True,doctype='')xmlFile=open(str(orderNumber)+“.xml”,“w”)xmlFile.write(treeStr)