1.简单的XML文件内容如下:
The Cathedral & the Bazaar
Eric S. Raymond
Making TeX Work
Norman Walsh
2.代码
#! /usr/bin/python
import xml.dom.minidom
from xml.dom.minidom import Node
doc = xml.dom.minidom.parse("books.xml")
mapping = {}
for node in doc.getElementsByTagName("book"):
isbn = node.getAttribute("isbn")
L = node.getElementsByTagName("title")
for node2 in L:
title = ""
for node3 in node2.childNodes:
if node3.nodeType == Node.TEXT_NODE:
title += node3.data
mapping[isbn] = title
# mapping now has the same value as in the SAX example:
print(mapping)
不过这样写我感觉有问题!
以下是我整理的代码处理XML的常用操作:
1.如果配置信息如下:
routelist
route
ip
port
delay
比如说:可以存储些连接配置DB的相关信息进来!
2.对应的解析XML的PY代码如下:
#=============================================
#作用:解析XML读取配置信息。整理归档,以后如果有
#DB信息要读取的话直接使用
#=============================================
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('b.xml') # parse an XML file by name
config_element = dom1.getElementsByTagName("config")[0]
routelist = config_element.getElementsByTagName("routelist")[0]
route = config_element.getElementsByTagName("route")[0]
ip = config_element.getElementsByTagName("ip")[0]
port = config_element.getElementsByTagName("port")[0]
delay = config_element.getElementsByTagName("delay")[0]
print getText(routelist.childNodes)
便可以将配置信息的内容全部遍历一遍的呀!
上面这种是XML中只有两级标签结构,如果有三层的话
案例二:
XML格式如下:
192.168.100.40
root
321
mydb
error
mysql
192.168.100.40
root
321
muil
users
mysql
GET
阅读(3518) | 评论(4) | 转发(0) |