XML Declaration standalone=“yes” lxml

前端 未结 5 1208
暗喜
暗喜 2020-12-20 13:01

I have an xml I am parsing, making some changes and saving out to a new file. It has the declaration

5条回答
  •  死守一世寂寞
    2020-12-20 13:18

    If You want to disable outputting standalone at all pass None instead of True or False. Sounds logical but took some time to actually find and test it.

    etree.tostring(tree, xml_declaration = True, encoding='utf-8', standalone=None)
    

    or using context manager and stream etree.xmlfile serialization:

    with etree.xmlfile(open('/tmp/test.xml'), encoding='utf-8') as xf:
        xf.write_declaration(standalone=None)
        with xf.element('html'):
            with xf.element('body'):
                element = etree.Element('p')
                element.text = 'This is paragraph'
                xf.write(element)
    

提交回复
热议问题