python minidom不关闭<xml标签>

2 投票
2 回答
669 浏览
提问于 2025-04-16 23:51

我在使用minidom的时候遇到了一些奇怪的情况。我运行了以下代码:

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标签。我真的不知道为什么它会让文档保持打开状态。有没有人遇到过同样的问题?还是我只是忘记了一些非常明显的东西,以至于我看不到问题所在?

2 个回答

1

你的XML是有效的:

可以看看这个链接:http://en.wikipedia.org/wiki/XML_Schema_%28W3C%29

你不需要关闭声明。

6

这个 <?xml ... ?> 不是一个标签,而是一个叫做 XML声明 的东西。你不需要给它加上结束标记,你的文档完全没问题。

撰写回答