99 votes

Comment écrire une déclaration XML en utilisant xml.etree.ElementTree

Je suis en train de générer un document XML en Python à l'aide d'un fichier ElementTree mais le tostring n'inclut pas une fonction Déclaration XML lors de la conversion en texte clair.

from xml.etree.ElementTree import Element, tostring

document = Element('outer')
node = SubElement(document, 'inner')
node.NewValue = 1
print tostring(document)  # Outputs "<outer><inner /></outer>"

J'ai besoin que ma chaîne inclue la déclaration XML suivante :

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>

Cependant, il ne semble pas y avoir de moyen documenté de le faire.

Existe-t-il une méthode appropriée pour rendre la déclaration XML dans un fichier de type ElementTree ?

3voto

Kirill Malakhov Points 664

Facile

Exemple pour Python 2 et 3 ( codage doit être utf8 ) :

import xml.etree.ElementTree as ElementTree

tree = ElementTree.ElementTree(ElementTree.fromstring('<xml><test>123</test></xml>'))
root = tree.getroot()
print(ElementTree.tostring(root, encoding='utf8', method='xml'))

Dans Python 3.8, il y a xml_déclaration pour ce genre de choses :

Nouveau dans la version 3.8 : Les fonctions xml_declaration et default_namespace par défaut.

xml.etree.ElementTree.tostring(élément, encodage="us-ascii", method="xml", *, xml_declaration=None, default_namespace=None, short_empty_elements=True) Génère une représentation sous forme de chaîne d'un élément XML y compris tous les sous-éléments. element est une instance d'élément. encoding 1 est l'encodage de sortie (par défaut, US-ASCII). Utilisez encoding="unicode" pour générer une chaîne Unicode (sinon, un bytestring est générée). method est soit "xml", "html" ou "text" (par défaut "xml"). (la valeur par défaut est "xml"). xml_declaration, default_namespace et short_empty_elements a la même signification que dans ElementTree.write(). Renvoie une chaîne de caractères (facultativement) codée contenant les données XML.

Exemple pour Python 3.8 et plus :

import xml.etree.ElementTree as ElementTree

tree = ElementTree.ElementTree(ElementTree.fromstring('<xml><test>123</test></xml>'))
root = tree.getroot()
print(ElementTree.tostring(root, encoding='unicode', method='xml', xml_declaration=True))

2voto

Andriy Points 409

L'exemple minimal de travail avec ElementTree utilisation du paquet :

import xml.etree.ElementTree as ET

document = ET.Element('outer')
node = ET.SubElement(document, 'inner')
node.text = '1'
res = ET.tostring(document, encoding='utf8', method='xml').decode()
print(res)

la sortie est :

<?xml version='1.0' encoding='utf8'?>
<outer><inner>1</inner></outer>

1voto

Novak Points 1757

Une autre option assez simple consiste à concaténer l'en-tête souhaité à la chaîne de caractères xml comme ceci :

xml = (bytes('<?xml version="1.0" encoding="UTF-8"?>\n', encoding='utf-8') + ET.tostring(root))
xml = xml.decode('utf-8')
with open('invoice.xml', 'w+') as f:
    f.write(xml)

0voto

Alessandro Points 38

J'utiliserais ET :

try:
    from lxml import etree
    print("running with lxml.etree")
except ImportError:
    try:
        # Python 2.5
        import xml.etree.cElementTree as etree
        print("running with cElementTree on Python 2.5+")
    except ImportError:
        try:
            # Python 2.5
            import xml.etree.ElementTree as etree
            print("running with ElementTree on Python 2.5+")
        except ImportError:
            try:
                # normal cElementTree install
                import cElementTree as etree
                print("running with cElementTree")
            except ImportError:
               try:
                   # normal ElementTree install
                   import elementtree.ElementTree as etree
                   print("running with ElementTree")
               except ImportError:
                   print("Failed to import ElementTree from any known place")

document = etree.Element('outer')
node = etree.SubElement(document, 'inner')
print(etree.tostring(document, encoding='UTF-8', xml_declaration=True))

0voto

Rebecca Fallon Points 1

Cela fonctionne si vous voulez juste imprimer. J'obtiens une erreur lorsque j'essaie de l'envoyer dans un fichier...

import xml.dom.minidom as minidom
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element, SubElement, Comment, tostring

def prettify(elem):
    rough_string = ET.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="  ")

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X