XML writing tools for Python

后端 未结 8 1045
眼角桃花
眼角桃花 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 09:56

    Another way is using the E Factory builder from lxml (available in Elementtree too)

    >>> from lxml import etree
    
    >>> from lxml.builder import E
    
    >>> def CLASS(*args): # class is a reserved word in Python
    ...     return {"class":' '.join(args)}
    
    >>> html = page = (
    ...   E.html(       # create an Element called "html"
    ...     E.head(
    ...       E.title("This is a sample document")
    ...     ),
    ...     E.body(
    ...       E.h1("Hello!", CLASS("title")),
    ...       E.p("This is a paragraph with ", E.b("bold"), " text in it!"),
    ...       E.p("This is another paragraph, with a", "\n      ",
    ...         E.a("link", href="http://www.python.org"), "."),
    ...       E.p("Here are some reserved characters: ."),
    ...       etree.XML("

    And finally an embedded XHTML fragment.

    "), ... ) ... ) ... ) >>> print(etree.tostring(page, pretty_print=True)) This is a sample document

    Hello!

    This is a paragraph with bold text in it!

    This is another paragraph, with a link.

    Here are some reservered characters: <spam&egg>.

    And finally an embedded XHTML fragment.

提交回复
热议问题