Question

Je veux ajouter doctypes à mes documents XML que je générer avec etree de LXML.

Cependant, je ne peux pas comprendre comment ajouter un type de document. Hardcoding et concating la chaîne n'est pas une option.

Je me attendais quelque chose le long des lignes de la façon dont sont ajoutées dans etree de PI:

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

Mais il ne fonctionne pas pour moi. Comment ajouter un à un document XML avec lxml?

Était-ce utile?

La solution

Vous pouvez créer votre document avec un doctype pour commencer:

# 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")

impressions:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE root SYSTEM "test" [
<!ENTITY tasty "cheese">
<!ENTITY eacute "&#233;">
]>
<root>
<a>cheese soufflé</a>
</root>

Si vous souhaitez ajouter un type de document XML à certains qui n'a pas été créé avec un, vous pouvez d'abord créer un avec le doctype souhaité (comme ci-dessus), puis copiez votre XML DOCTYPE-moins en elle:

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")

impressions:

<?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>

Est-ce que vous cherchez?

Autres conseils

Cela a fonctionné pour moi:

print etree.tostring(tree, pretty_print=True, xml_declaration=True, encoding="UTF-8", doctype="<!DOCTYPE TEST_FILE>")

Le PI est effectivement ajouté comme élément précédent de « doc ». Ainsi, ce n'est pas un enfant de « doc ». Vous devez utiliser "doc.getroottree ()"

Voici un exemple:

>>> 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>

avec 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>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top