Tôi có một số mã python để tạo một số văn bản XML với xml.dom.minidom. Ngay bây giờ, tôi chạy nó từ thiết bị đầu cuối và nó kết quả đầu ra cho tôi một XML có cấu trúc như là một kết quả. Tôi muốn nó cũng tạo ra một tập tin XML và lưu nó vào đĩa của tôi. Làm thế nào có thể được thực hiện?Làm thế nào để lưu tệp XML vào đĩa bằng python?
Đây là những gì tôi có:
import xml
from xml.dom.minidom import Document
import copy
class dict2xml(object):
doc = Document()
def __init__(self, structure):
if len(structure) == 1:
rootName = str(structure.keys()[0])
self.root = self.doc.createElement(rootName)
self.doc.appendChild(self.root)
self.build(self.root, structure[rootName])
def build(self, father, structure):
if type(structure) == dict:
for k in structure:
tag = self.doc.createElement(k)
father.appendChild(tag)
self.build(tag, structure[k])
elif type(structure) == list:
grandFather = father.parentNode
tagName = father.tagName
# grandFather.removeChild(father)
for l in structure:
tag = self.doc.createElement(tagName.rstrip('s'))
self.build(tag, l)
father.appendChild(tag)
else:
data = str(structure)
tag = self.doc.createTextNode(data)
father.appendChild(tag)
def display(self):
print self.doc.toprettyxml(indent=" ")
chỉ này tạo ra XML. Làm thế nào tôi có thể lưu nó dưới dạng tập tin trên máy tính để bàn?
Vẫn không thể quản lý nó để làm việc –
Chính xác bạn đã làm gì Thử câu hỏi đã chỉnh sửa của bạn chỉ bao gồm mã cho việc in ấn XML đẹp đến bàn điều khiển, nó không bao gồm nỗ lực của bạn để sử dụng 'writexml()', vì vậy chúng tôi không thể giúp bạn khắc phục điều đó. 'writexml()' và làm thế nào nó không hoạt động (có một thông báo lỗi? hoặc nó không hoạt động như bạn dự định?) –
Mở ở chế độ "wb" didnt làm việc cho tôi tuy nhiên chỉ "w" làm việc –