2008-08-27 82 views
15

這裏是我的示例代碼:如何在python創建XML文檔

from xml.dom.minidom import * 
def make_xml(): 
    doc = Document() 
    node = doc.createElement('foo') 
    node.innerText = 'bar' 
    doc.appendChild(node) 
    return doc 
if __name__ == '__main__': 
    make_xml().writexml(sys.stdout) 

當我運行上面的代碼中,我得到這樣的:

<?xml version="1.0" ?> 
<foo/> 

我想獲得:

<?xml version="1.0" ?> 
<foo>bar</foo> 

我剛剛猜到有一個innerText屬性,它沒有給出編譯器錯誤,但似乎沒有工作......我如何去創建一個文本點頭è?

回答

8

在對象上設置屬性不會給出編譯時或運行時錯誤,如果對象無法訪問它,它將不起作用(即「node.noSuchAttr = 'bar'」也不會給出錯誤)。

除非你需要的minidom特定的功能,我想看看ElementTree

import sys 
from xml.etree.cElementTree import Element, ElementTree 

def make_xml(): 
    node = Element('foo') 
    node.text = 'bar' 
    doc = ElementTree(node) 
    return doc 

if __name__ == '__main__': 
    make_xml().write(sys.stdout) 
10

@Daniel

感謝您的答覆,我也想通了如何與minidom命名(我這樣做不敢肯定VS的minidom命名

 

from xml.dom.minidom import * 
def make_xml(): 
    doc = Document(); 
    node = doc.createElement('foo') 
    node.appendChild(doc.createTextNode('bar')) 
    doc.appendChild(node) 
    return doc 
if __name__ == '__main__': 
    make_xml().writexml(sys.stdout) 
 

了ElementTree之間的差異)的我發誓,我張貼我的問題之前嘗試這個...