Creazione di un doctype con eTree di lxml
-
13-09-2019 - |
Domanda
Voglio aggiungere DOCTYPE ai miei documenti XML che sto generando con eTree di LXML.
Comunque non riesco a capire come aggiungere un doctype. Hardcoding e concating la stringa non è un'opzione.
Mi aspettavo qualcosa sulla falsariga di come PI di sono aggiunti in eTree:
pi = etree.PI(...)
doc.addprevious(pi)
Ma non funziona per me. Come aggiungere un a un documento XML con lxml?
Soluzione
È possibile creare il documento con un doctype per cominciare:
# 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")
stampe:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE root SYSTEM "test" [
<!ENTITY tasty "cheese">
<!ENTITY eacute "é">
]>
<root>
<a>cheese soufflé</a>
</root>
Se si desidera aggiungere un doctype a qualche XML che non è stato creato con uno, è possibile creare prima uno con il doctype desiderato (come sopra), quindi copiare il tuo XML DOCTYPE-less in esso:
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")
stampe:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE root SYSTEM "test" [
<!ENTITY tasty "cheese">
<!ENTITY eacute "é">
]>
<root><test/><a>whatever</a><end_test/></root>
E 'questo che stai cercando?
Altri suggerimenti
Questo ha funzionato per me:
print etree.tostring(tree, pretty_print=True, xml_declaration=True, encoding="UTF-8", doctype="<!DOCTYPE TEST_FILE>")
Il PI viene effettivamente aggiunto come elemento precedente da "doc". Così, non è un figlio di "doc". È necessario utilizzare "doc.getroottree ()"
Ecco un esempio:
>>> 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>
con 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>