2011-08-18 67 views
2

我遇到了使用minidom的奇怪行爲。我運行下面的代碼:python minidom不關閉<xml tag>

import os 
import sys 
from xml.dom import minidom 
def generateReleaseXMLFile(): 
    modelPath = "%./model/" 
    # Create the parser 
    xsydoc = minidom.Document() 
    # Create the element ScriptModelVersion 
    scriptModelVersion = xsydoc.createElement('ScriptModelVersion') 
    # Assign all the attributes 
    scriptModelVersion.setAttribute("Major", "1") 
    scriptModelVersion.setAttribute("Minor", "2") 
    scriptModelVersion.setAttribute("Patch", "3") 
    scriptModelVersion.setAttribute("ReseaseDate", "2011-05-20") 
    # Append the root to the document 
    xsydoc.appendChild(scriptModelVersion) 
    # Create the file descriptor 
    fdesc = open(modelPath+"Release.xml", "w") 
    # Write the file 
    fdesc.write(xsydoc.toprettyxml()) 
    # Close the file 
    fdesc.close() 
    print xsydoc.toprettyxml() 

generateReleaseXMLFile() 

它會生成以下的輸出:

<?xml version="1.0" ?> 
<ScriptModelVersion Major="9" Minor="0" Patch="1" ReleaseDate="2011-05-20"/> 

的內部消除XML標籤關閉。 我真的不知道爲什麼它保持文檔打開。有沒有人遇到同樣的問題?或者我只是忘記了一些真正顯而易見的思想,我只是看不到這個問題?

回答

6

<?xml ... ?>不是標籤,而是XML Declaration。沒有必要關閉它,你的文檔形狀完美。

+0

你對!太愚蠢了......一個小時我瘋了......我甚至都沒有想過這件事。我打開了我創建的其他文檔,當然如你所說。恥辱我! :) – Stefano