XML writing tools for Python

后端 未结 8 1044
眼角桃花
眼角桃花 2020-12-23 09:30

I\'m currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven\'t heard of?

Thi

8条回答
  •  攒了一身酷
    2020-12-23 10:00

    I assume that you're actually creating an XML DOM tree, because you want to validate that what goes into this file is valid XML, since otherwise you'd just write a static string to a file. If validating your output is indeed your goal, then I'd suggest

    from xml.dom.minidom import parseString
    
    doc = parseString("""
        
            
        
        
            

    And I like the fact that 3 > 1

    """) with open("foo.xhtml", "w") as f: f.write( doc.toxml() )

    This lets you just write the XML you want to output, validate that it's correct (since parseString will raise an exception if it's invalid) and have your code look much nicer.

    Presumably you're not just writing the same static XML every time and want some substitution. In this case I'd have lines like

    var a = '%(message)s'
    

    and then use the % operator to do the substitution, like

    """ % {"message": "I love á letters"})
    

提交回复
热议问题