第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > python读取xml配置_python读取xml配置文件实例

python读取xml配置_python读取xml配置文件实例

时间:2019-03-14 02:53:27

相关推荐

python读取xml配置_python读取xml配置文件实例

有如下的xml配置文件,名字为config.xml: 代码示例:

server1

server2

account

pwd

python代码 解析xml配置文件: 代码示例:

from xml.dom.minidom import parse, parsestring

def gettext(nodelist):

rc = ""

for node in nodelist:

if node.nodetype == node.text_node:

rc = rc + node.data

return rc

if __name__=="__main__":

dom1 = parse('config.xml') # parse an xml file by name

config_element = dom1.getelementsbytagname("config")[0]

servers = config_element.getelementsbytagname("server")

for server in servers:

print gettext(server.childnodes)

显示结果:

dd

python读取xml配置文件,主要是perse的getelementsbytagname()函数,它返回的是nodelist对象。

python 的library reference上如下解释nodelist:(脚本学堂 www.#)

a nodelist represents a sequence of nodes. these objects are used in two ways in the dom core recommendation: the element objects provides one as its list of child nodes, and the getelementsbytagname() and getelementsbytagnamens() methods of node return objects with this interface to represent query results.

对nodelist中的每个node,调用gettext函数,如果是text_node类型的,则将其打印出。

node的childnodes的说明:

childnodes

a list of nodes contained within this node. this is a read-only attribute.

dom的常用节点: 节点类型 例子

document type

processing instruction

element

car

lsberg

attribute type="beer"

text carlsberg

node 有个nodevalue属性,开始不知道和node的data属性有何差别,后来查了dom的文档,如下解释:

xml 对象的节点值。如果 xml 对象是一个文本节点,则 nodetype 为 3,nodevalue 是节点的文本。如果 xml 对象是一个 xml 元素(nodetype 为 1),则 nodevalue 为 null 且只读

在python里试了一下,对普通的文本节点,如“

mail.”,nodevalue是1,为了要显示其文本内容,用.data属性和用.nodevalue属性是效果一样的,如: 代码示例:

rc = ""

for node in node.childnodes:

if node.nodetype in ( node.text_node, node.

cdata_section_node):

rc = rc + node.nodevalue

print rc

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。