创建具有LXML的etree一个DOCTYPE
-
13-09-2019 - |
题
我要的文档类型添加到我与LXML的etree生成我的XML文档。
但是我不能找出如何添加一个DOCTYPE。硬编码和concating字符串不是一个选项。
我期待沿如何PI的线在etree添加的东西:
pi = etree.PI(...)
doc.addprevious(pi)
但它不是为我工作。如何将与LXML添加到XML文档?
解决方案
您可以创建一个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>
如果您想将文档类型添加到不是一个创造了一些XML,你可以先创建一个与所需的文档类型(如上所述),那么你的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>
这就是你要找的是什么?
其他提示
这为我工作:
print etree.tostring(tree, pretty_print=True, xml_declaration=True, encoding="UTF-8", doctype="<!DOCTYPE TEST_FILE>")
在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>
不隶属于 StackOverflow