XML writing tools for Python

后端 未结 8 1007
眼角桃花
眼角桃花 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:23

    There's always SimpleXMLWriter, part of the ElementTree toolkit. The interface is dead simple.

    Here's an example:

    from elementtree.SimpleXMLWriter import XMLWriter
    import sys
    
    w = XMLWriter(sys.stdout)
    html = w.start("html")
    
    w.start("head")
    w.element("title", "my document")
    w.element("meta", name="generator", value="my application 1.0")
    w.end()
    
    w.start("body")
    w.element("h1", "this is a heading")
    w.element("p", "this is a paragraph")
    
    w.start("p")
    w.data("this is ")
    w.element("b", "bold")
    w.data(" and ")
    w.element("i", "italic")
    w.data(".")
    w.end("p")
    
    w.close(html)
    
    0 讨论(0)
  • 2020-12-23 10:23

    don't you actually want something like:

    html(head(script(type='text/javascript', content='var a = ...')),
    body(h1('And I like the fact that 3 < 1'), p('just some paragraph'))
    

    I think I saw something like that somewhere. This would be wonderful.

    EDIT: Actually, I went and wrote a library today to do just that: magictree

    You can use it like this:

    from magictree import html, head, script, body, h1, p
    root = html(
             head(
               script('''var a = 'I love &amp;aacute; letters''', 
                      type='text/javascript')),
             body(
               h1('And I like the fact that 3 > 1')))
    
    # root is a plain Element object, like those created with ET.Element...
    # so you can write it out using ElementTree :)
    tree = ET.ElementTree(root)
    tree.write('foo.xhtml')
    

    The magic in magictree lies in how the importing works: The Element factories are created when needed. Have a look at the source, it is based on an answer to another StackOverflow question.

    0 讨论(0)
提交回复
热议问题