Skip to main content
 首页 » 编程设计

python之从 Python 中的字典创建 XML

2025年05月04日8telwanggs

我对 XML 和 Python 都很陌生,所以请忽略 .我正在尝试将字典直接解压缩为 XML 格式。我的代码片段如下:

from xml.dom.minidom import Document 
def make_xml(dictionary): 
    doc = Document() 
    result = doc.createElement('result') 
    doc.appendChild(result)     
 
    for key in dictionary: 
        attrib = doc.createElement(key) 
        result.appendChild(attrib) 
        value = doc.createTextNode(dictionary[key]) 
        attrib.appendChild(value) 
 
    print doc 

我期待格式的回答

<xml> 
 <result> 
  <attrib#1>value#1</attrib#1> 
   ... 

但是我得到的只是

<xml.dom.minidom.Document instance at 0x01BE6130> 

请帮忙

请您参考如下方法:

你还没有检查

http://docs.python.org/library/xml.dom.minidom.html

文档。

查看 toxml() 或 prettyprettyxml() 方法。