How to create <!DOCTYPE> with Python's cElementTree

后端 未结 4 2011
北海茫月
北海茫月 2020-11-30 14:42

I have tried to use the answer in this question, but can\'t make it work: How to create "virtual root" with Python's ElementTree?

Here\'s my code:

4条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 15:29

    You could set xml_declaration argument on write function to False, so output won't have xml declaration with encoding, then just append what header you need manually. Actually if you set your encoding as 'utf-8' (lowercase), xml declaration won't be added too.

    import xml.etree.cElementTree as ElementTree
    
    tree = ElementTree.Element('tmx', {'version': '1.4a'})
    ElementTree.SubElement(tree, 'header', {'adminlang': 'EN'})
    ElementTree.SubElement(tree, 'body')
    
    with open('myfile.tmx', 'wb') as f:
        f.write(''.encode('utf8'))
        ElementTree.ElementTree(tree).write(f, 'utf-8')
    

    Resulting file (newlines added manually for readability):

    
    
    
        

提交回复
热议问题