20

这是我的示例代码:

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 属性,它没有给出编译器错误,但似乎不起作用......我该如何创建一个文本节点?

4

2 回答 2

13

@丹尼尔

感谢您的回复,我还想出了如何使用 minidom 来做到这一点(我不确定 ElementTree 与 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)

我发誓我在发布我的问题之前尝试过这个......

于 2008-08-27T00:42:32.723 回答
9

在对象上设置属性不会给出编译时或运行时错误,如果对象不访问它,它只会做任何有用的事情(即“ 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)
于 2008-08-27T00:35:29.807 回答