2013-03-12 64 views
29

Tôi đang tạo một tài liệu XML bằng Python sử dụng một ElementTree, nhưng hàm tostring không bao gồm một XML declaration khi chuyển đổi sang văn bản thô.Cách viết khai báo XML bằng cách sử dụng 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>" 

Tôi cần chuỗi của tôi bao gồm các khai báo XML sau đây:

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

Tuy nhiên, có dường như không có bất kỳ cách ghi nhận để làm điều này.

Có phương pháp thích hợp để hiển thị khai báo XML trong một số ElementTree không?

Trả lời

50

Tôi ngạc nhiên khi thấy rằng có vẻ không phải là một cách với ElementTree.tostring(). tuy nhiên bạn có thể sử dụng ElementTree.ElementTree.write() để viết tài liệu XML của bạn vào một tập tin giả:

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 

Xem this question. Thậm chí sau đó, tôi không nghĩ rằng bạn có thể nhận được thuộc tính 'độc lập' của bạn mà không cần tự mình chuẩn bị trước.

+0

tại sao bạn xác định biến "nút" ở đây? –

+3

Cảm ơn dòng này et.write (f, encoding = 'utf-8', xml_declaration = True) đã lưu ngày của tôi –

15

Tôi sẽ sử dụng lxml (xem http://lxml.de/api.html).

Sau đó, bạn có thể:

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

tôi gặp phải vấn đề này thời gian gần đây, sau khi một số digging của mã, tôi thấy đoạn mã sau đây là định nghĩa của chức năng 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, {}) 

Vì vậy, câu trả lời là, nếu bạn cần viết tiêu đề XML để tập tin của bạn , đặt đối số encoding khác với utf-8 hoặc us-ascii, ví dụ: UTF-8

+0

Nó sẽ là một hack tốt đẹp mặc dù dễ vỡ, nhưng nó dường như không hoạt động (mã hóa có thể thấp hơn) cased trước đó). Ngoài ra, 'ElementTree.ElementTree.write()' được ghi lại để có một tham số 'xml_declaration' (xem câu trả lời được chấp nhận). Nhưng 'ElementTree.tostring() 'không có tham số đó, là phương thức được hỏi trong câu hỏi gốc. –

0

Tôi sẽ sử dụng 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

này hoạt động nếu bạn chỉ muốn in. Nhận được một lỗi khi tôi cố gắng gửi nó vào một tập tin ...

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 viết một tuyên bố mã hóa XML với encoding = 'utf8'

mẫu Python 2 mã:

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

Output:

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

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

Trong Python 3, ký tự thoát sẽ được hiển thị trong phần khai báo khi in. '' –

Các vấn đề liên quan