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

后端 未结 4 2010
北海茫月
北海茫月 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:22

    I couldn't find a solution to this problem either using vanilla ElementTree, and the solution proposed by demalexx created non-valid XML that was rejected by my application (DITA). What I propose is a workaround involving other modules and it works perfectly for me.

    import re
    # found no way for cleanly specify a  stanza in ElementTree so
    # so we substitute the current  stanza with a full \n' \
                     '\n'
    
    target_xml = re.sub(u"\<\?xml .+?>", new_header, source_xml)
    with open(filename, 'w') as catalog_file:
        catalog_file.write(target_xml.encode('utf8'))
    

提交回复
热议问题