電子工廠提供了一個簡單而緊湊的語法來生成 XML 和 HTML:
>>> 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: <spam&egg>."),
... etree.XML("<p>And finally an embedded XHTML fragment.</p>"),
... )
... )
... )
>>> print(etree.tostring(page, pretty_print=True))
<html>
<head>
<title>This is a sample document</title>
</head>
<body>
<h1 class="title">Hello!</h1>
<p>This is a paragraph with <b>bold</b> text in it!</p>
<p>This is another paragraph, with a
<a href="http://www.python.org">link</a>.</p>
<p>Here are some reserved characters: <spam&egg>.</p>
<p>And finally an embedded XHTML fragment.</p>
</body>
於屬性訪問的元素創建可以很容易地爲 XML 語言構建一個簡單的詞彙表:
>>> from lxml.builder import ElementMaker # lxml only !
>>> E = ElementMaker(namespace="http://my.de/fault/namespace",
... nsmap={'p' : "http://my.de/fault/namespace"})
>>> DOC = E.doc
>>> TITLE = E.title
>>> SECTION = E.section
>>> PAR = E.par
>>> my_doc = DOC(
... TITLE("The dog and the hog"),
... SECTION(
... TITLE("The dog"),
... PAR("Once upon a time, ..."),
... PAR("And then ...")
... ),
... SECTION(
... TITLE("The hog"),
... PAR("Sooner or later ...")
... )
... )
>>> print(etree.tostring(my_doc, pretty_print=True))
<p:doc xmlns:p="http://my.de/fault/namespace">
<p:title>The dog and the hog</p:title>
<p:section>
<p:title>The dog</p:title>
<p:par>Once upon a time, ...</p:par>
<p:par>And then ...</p:par>
</p:section>
<p:section>
<p:title>The hog</p:title>
<p:par>Sooner or later ...</p:par>
</p:section>
</p:doc>
其中一個例子是模塊 lxml. builder,它爲 HTML 提供了一個詞彙表。
在處理多個名稱空間時,最好爲每個名稱空間 URI 定義一個 ElementMaker。 同樣,請注意上面的示例是如何在命名常量中預定義標記構建器的。 這使得將一個命名空間的所有標記聲明放到一個 Python 模塊中並從那裏導入 / 使用標記名稱常量變得非常容易。 這樣可以避免輸入錯誤或意外丟失名稱空間等缺陷。