我想在我使用LXML的etree生成的XML文档中添加doctypes。
但是我无法弄清楚如何添加doctype。硬编码和连接字符串不是一种选择。
我期待在etree中添加PI的方式:
pi = etree.PI(...)
doc.addprevious(pi)
但它不适合我。如何使用lxml?
添加到xml文档答案 0 :(得分:28)
这对我有用:
print etree.tostring(tree, pretty_print=True, xml_declaration=True, encoding="UTF-8", doctype="<!DOCTYPE TEST_FILE>")
答案 1 :(得分:9)
您可以使用doctype创建文档:
# Adapted from example on http://codespeak.net/lxml/tutorial.html
import lxml.etree as et
import StringIO
s = """<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE root SYSTEM "test" [ <!ENTITY tasty "cheese">
<!ENTITY eacute "é"> ]>
<root>
<a>&tasty; soufflé</a>
</root>
"""
tree = et.parse(StringIO.StringIO(s))
print et.tostring(tree, xml_declaration=True, encoding="utf-8")
打印:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE root SYSTEM "test" [
<!ENTITY tasty "cheese">
<!ENTITY eacute "é">
]>
<root>
<a>cheese soufflé</a>
</root>
如果要将doctype添加到某些未使用doc创建的XML中,可以先创建一个带有所需doctype的文档(如上所述),然后将无doctype的XML复制到其中:
xml = et.XML("<root><test/><a>whatever</a><end_test/></root>")
root = tree.getroot()
root[:] = xml
root.text, root.tail = xml.text, xml.tail
print et.tostring(tree, xml_declaration=True, encoding="utf-8")
打印:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE root SYSTEM "test" [
<!ENTITY tasty "cheese">
<!ENTITY eacute "é">
]>
<root><test/><a>whatever</a><end_test/></root>
这就是你要找的东西吗?
答案 2 :(得分:4)
PI实际上是作为“doc”中的前一个元素添加的。因此,它不是“doc”的孩子。您必须使用“doc.getroottree()”
以下是一个例子:
>>> root = etree.Element("root")
>>> a = etree.SubElement(root, "a")
>>> b = etree.SubElement(root, "b")
>>> root.addprevious(etree.PI('xml-stylesheet', 'type="text/xsl" href="my.xsl"'))
>>> print etree.tostring(root, pretty_print=True, xml_declaration=True, encoding='utf-8')
<?xml version='1.0' encoding='utf-8'?>
<root>
<a/>
<b/>
</root>
使用getroottree():
>>> print etree.tostring(root.getroottree(), pretty_print=True, xml_declaration=True, encoding='utf-8')
<?xml version='1.0' encoding='utf-8'?>
<?xml-stylesheet type="text/xsl" href="my.xsl"?>
<root>
<a/>
<b/>
</root>