LXML の etree で生成している XML ドキュメントに Doctype を追加したいと考えています。
ただし、doctype を追加する方法がわかりません。文字列のハードコーディングと連結はオプションではありません。
PIがetreeに追加される方法に沿って何かを期待していました:
pi = etree.PI(...)
doc.addprevious(pi)
しかし、それは私にとってはうまくいきません。lxmlを使用してxmlドキュメントにaを追加するには?
LXML の etree で生成している XML ドキュメントに Doctype を追加したいと考えています。
ただし、doctype を追加する方法がわかりません。文字列のハードコーディングと連結はオプションではありません。
PIがetreeに追加される方法に沿って何かを期待していました:
pi = etree.PI(...)
doc.addprevious(pi)
しかし、それは私にとってはうまくいきません。lxmlを使用してxmlドキュメントにaを追加するには?
これは私のために働いた:
print etree.tostring(tree, pretty_print=True, xml_declaration=True, encoding="UTF-8", doctype="<!DOCTYPE TEST_FILE>")
まず、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 を使用して作成されていない XML に Doctype を追加する場合は、最初に (上記のように) 目的の Doctype を使用して 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>
それはあなたが探しているものですか?
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>