【问题标题】:how to write the opening of an xml doc in lxml?如何在 lxml 中编写 xml 文档的开头?
【发布时间】:2015-02-11 10:35:55
【问题描述】:

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

【问题讨论】:

    标签: python xml lxml cxml


    【解决方案1】:

    您可以将它们作为参数传递给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>
    

    【讨论】:

    • 完美运行。要将其写入文件,我使用了这个:treeStr = ET.tostring(topline, encoding="UTF-8", xml_declaration=True, doctype='''&lt;!DOCTYPE cXML SYSTEM "http://xml.cXML.org/schemas/cXML/1.2.011/InvoiceDetail.dtd"&gt;''') xmlFile = open(str(orderNumber) + ".xml", 'w') xmlFile.write(treeStr)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多