lxmlののetreeとDOCTYPEを作成します
-
13-09-2019 - |
質問
私はLXMLのetreeで生成しています私のXML文書に文書型を追加したいです。
しかし、私はDOCTYPEを追加する方法を見つけ出すことはできません。ハードコードや文字列をconcatingはオプションではありません。
私はetreeに追加する方法PIのの線に沿って何かを期待していた。
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>
あなたは1で作成されていないいくつかのXMLに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>
あなたが探しているものということですか?
他のヒント
これは私のために働いてます:
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