19

LXML の etree で生成している XML ドキュメントに Doctype を追加したいと考えています。

ただし、doctype を追加する方法がわかりません。文字列のハードコーディングと連結はオプションではありません。

PIがetreeに追加される方法に沿って何かを期待していました:

pi = etree.PI(...)
doc.addprevious(pi)

しかし、それは私にとってはうまくいきません。lxmlを使用してxmlドキュメントにaを追加するには?

4

3 に答える 3

36

これは私のために働いた:

print etree.tostring(tree, pretty_print=True, xml_declaration=True, encoding="UTF-8", doctype="<!DOCTYPE TEST_FILE>")
于 2012-07-02T18:02:36.177 に答える
11

まず、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 "&#233;"> ]>
<root>
<a>&tasty; souffl&eacute;</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 "&#233;">
]>
<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 "&#233;">
]>
<root><test/><a>whatever</a><end_test/></root>

それはあなたが探しているものですか?

于 2009-07-08T17:33:40.877 に答える
7

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>
于 2010-05-18T15:28:42.070 に答える