gpt4 book ai didi

python - 用于 Python 的 XML 编写工具

转载 作者:IT老高 更新时间:2023-10-28 21:48:47 25 4
gpt4 key购买 nike

我目前正在尝试 ElementTree,它看起来不错,它可以转义 HTML 实体等等。我是否错过了一些我从未听说过的真正美妙的东西?

这和我实际做的差不多:

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
<html><head><script type="text/javascript">var a = 'I love &amp;aacute;
letters'</script></head><body><h1>And I like the fact that 3 &gt; 1</h1>
</body></html>

最佳答案

另一种方法是使用 E Factory来自 lxml 的构建器(在 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: <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 reservered characters: &lt;spam&amp;egg&gt;.</p>
<p>And finally an embedded XHTML fragment.</p>
</body>
</html>

关于python - 用于 Python 的 XML 编写工具,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com