如何在python中创建一个xml文档 [英] How do I create an xml document in python

查看:25
本文介绍了如何在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)

这篇关于如何在python中创建一个xml文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆