XML writing tools for Python

Question :

XML writing tools for Python,

Answer :

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?

This is similar to what I’m actually doing:

import xml.etree.ElementTree as ET  root = ET.Element('html')  head = ET.SubElement(root,'head')  script = ET.SubElement(head,'script')  script.set('type','text/javascript')  script.text = "var a = 'I love á letters'"  body = ET.SubElement(root,'body')  h1 = ET.SubElement(body,'h1')  h1.text = "And I like the fact that 3 > 1"  tree = ET.ElementTree(root)  tree.write('foo.xhtml')    # more foo.xhtml  

And I like the fact that 3 > 1


Another way is using the builder from lxml (available in 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


This is a paragraph with bold text in it!

This is another paragraph, with a link.

Here are some reservered characters: .

And finally an embedded XHTML fragment.

That’s the answer XML writing tools for Python, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.

Disclaimer :

The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you

Read More  Best binary XML format for JavaME