Printing XML in Python

Once you have read an XML document or generated a new one, you might want to write them to a file, standard output, or even a string. Python provides many options to print out XML in string. Let me start from the very basic one.

print doc.toxml()

Easy! Now I will go to more advanced version of printing XML. Python offers good extension APIs and we should try them. First of all, don’t forget to import them and it’s rocking!

import sys
from xml.dom.ext import Print,PrettyPrint,XHtmlPrint,XHtmlPrettyPrint

Print(doc,sys.stdout)
PrettyPrint(doc,sys.stdout)
XHtmlPrint(doc,sys.stdout)
XHtmlPrettyPrint(doc,sys.stdout)

Very easy!

Technorati Tags: , , , , , , ,

Post new comment