如何在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)
当我运行上面的代码时,我得到了这个:
when I run the above code I get this:
<?xml version="1.0" ?>
<foo/>
我想得到:
<?xml version="1.0" ?>
<foo>bar</foo>
我只是猜测有一个 innerText 属性,它没有给出编译器错误,但似乎不起作用...我该如何创建文本节点?
I just guessed that there was an innerText property, it gives no compiler error, but does not seem to work... how do I go about creating a text node?
答
在对象上设置属性不会产生编译时或运行时错误,如果对象没有,它只会做任何有用的事情访问它(即node.noSuchAttr = 'bar'
"也不会给出错误).
Setting an attribute on an object won't give a compile-time or a run-time error, it will just do nothing useful if the object doesn't access it (i.e. "node.noSuchAttr = 'bar'
" would also not give an error).
除非您需要 minidom
的特定功能,否则我会查看 ElementTree
:
Unless you need a specific feature of minidom
, I would look at 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)