另一种方法是使用lxml中的E Factory构建器(也可以在Elementtree中使用)
>>> 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.
总有SimpleXMLWriter,它是ElementTree工具包的一部分.界面很简单.
这是一个例子:
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)
我假设你实际上是在创建一个XML DOM树,因为你想要验证进入这个文件的是有效的XML,因为否则你只需要在文件中写一个静态字符串.如果确认你的输出确实是你的目标,那么我建议
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() )
这使您可以只编写要输出的XML,验证它是否正确(因为如果它无效,parseString将引发异常)并让您的代码看起来更好.
据推测,您不仅每次都编写相同的静态XML,而且还需要进行一些替换.在这种情况下,我会有类似的行
var a = '%(message)s'
然后使用%运算符进行替换,例如