2013-03-12 16 views
29

Generuję dokument XML w Pythonie za pomocą ElementTree, ale funkcja nie zawiera XML declaration podczas konwersji do zwykłego tekstu.Jak napisać deklarację XML za pomocą xml.etree.ElementTree

from xml.etree.ElementTree import Element, tostring 

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

muszę mój ciąg zawierać następującą deklarację XML:

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

Jednak nie wydaje się być każdy udokumentowany sposób to zrobić.

Czy istnieje właściwa metoda renderowania deklaracji XML w ElementTree?

Odpowiedz

50

Jestem zaskoczony, że nie wydaje się być sposób z ElementTree.tostring(). Można jednak użyć ElementTree.ElementTree.write() napisać dokument XML do fałszywego pliku:

from io import BytesIO 
from xml.etree import ElementTree as ET 

document = ET.Element('outer') 
node = ET.SubElement(document, 'inner') 
et = ET.ElementTree(document) 

f = BytesIO() 
et.write(f, encoding='utf-8', xml_declaration=True) 
print(f.getvalue()) # your XML file, encoded as UTF-8 

Zobacz this question. Nawet wtedy nie sądzę, że możesz uzyskać swój "samodzielny" atrybut, nie pisząc go samodzielnie.

+0

dlaczego definiujesz tutaj zmienną "węzeł"? –

+3

Dzięki temu wierszowi et.write (f, encoding = 'utf-8', xml_declaration = True) uratował mój dzień –

15

Chciałbym użyć lxml (patrz http://lxml.de/api.html).

Następnie można:

from lxml import etree 
document = etree.Element('outer') 
node = etree.SubElement(document, 'inner') 
print(etree.tostring(document, xml_declaration=True)) 
3

I napotkać ten problem niedawno, po pewnym kopania kodu, znalazłem następujący fragment kodu jest definicja funkcji ElementTree.write

def write(self, file, encoding="us-ascii"): 
    assert self._root is not None 
    if not hasattr(file, "write"): 
     file = open(file, "wb") 
    if not encoding: 
     encoding = "us-ascii" 
    elif encoding != "utf-8" and encoding != "us-ascii": 
     file.write("<?xml version='1.0' encoding='%s'?>\n" % 
    encoding) 
    self._write(file, self._root, encoding, {}) 

Więc odpowiedź brzmi, czy trzeba napisać nagłówek XML do pliku , ustaw inny argument niż utf-8 lub us-ascii, np. UTF-8

+0

Byłby to miły, choć kruchy hack, ale nie wydaje się działać (kodowanie jest prawdopodobnie niższe- cased przed tym). Ponadto, "ElementTree.ElementTree.write()" ma udokumentowany parametr "xml_declaration" (patrz akceptowana odpowiedź). Ale "ElementTree.tostring() 'nie ma tego parametru, który był metodą zadaną w pytaniu oryginalnym. –

0

użyłbym 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)) 
0

To działa, jeśli po prostu chcesz wydrukować. Otrzymuję błąd, gdy próbuję wysłać go do pliku ...

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

If you include the encoding='utf8', you will get an XML header:

xml.etree.ElementTree.tostring pisze deklarację kodowania XML z encoding = 'UTF-8'

Przykładowy kod Python 2:

import xml.etree.ElementTree as ElementTree 

tree = ElementTree.ElementTree(
    ElementTree.fromstring('<xml><test>123</test></xml>') 
) 
root = tree.getroot() 

print 'without:' 
print ElementTree.tostring(root, method='xml') 
print 
print 'with:' 
print ElementTree.tostring(root, encoding='utf8', method='xml') 

wyjściowa:

without: 
<xml><test>123</test></xml> 

with: 
<?xml version='1.0' encoding='utf8'?> 
<xml><test>123</test></xml> 
+0

W Pythonie 3 znaki ucieczki będą widoczne w deklaracji podczas drukowania. '' –

Powiązane problemy