您的位置:首页 > 编程语言 > Python开发

python 读取xml的方法

2010-04-19 23:29 435 查看
python 读取xml 简单一例
2009-09-17 12:02
<?xml version="1.0" encoding="ISO-8859-1"?>
<-- ip.xml -->
<config>
<ip>
<p>192.168.1.1</p>
<p>192.168.1.2</p>
<p>192.168.1.3</p>
<p>192.168.1.4</p>
<p>192.168.1.5</p>
<p>192.168.1.6</p>
</ip>
<port>90</port>
</config>

from xml.dom import minidom
b = minidom.parse('ip.xml')
for i in b.childNodes[0].getElementsByTagName('p'):
print i.childNodes[0].toxml()

192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6

==================

#引入lib库
from xml.dom import minidom

#导入xml文件
dom = minidom.parse(fileXml)

#遍历子节点
for node in dom.childNodes:

for model in node.childNodes:
#得到子节点,保证节点的类型
if model.nodeType in ( node.ELEMENT_NODE, node.CDATA_SECTION_NODE):
#获取属性
sCat= model.getAttribute('name')

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/poson/archive/2008/12/17/3541360.aspx

======================

Python读取XML配置文件小例子 收藏
配置文件如下,名字为config.xml
<?xml version="1.0"?>
<config>
<server>server1</server>
<server>server2</server>
<account>account</account>
<pwd>pwd</pwd>
</config>

Python代码如下:
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)

显示结果:
mail.hundsun.com
mail.hundsun.comdd

Python读取XML配置文件还是比较简单的,主要是perse的getElementsByTagName()函数,它返回的是NodeList对象。
Python 的Library Reference上如下解释NodeList:
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 <!DOCTYPE food SYSTEM "food.dtd">
Processing instruction <?xml version="1.0"?>
Element <drink type="beer">Carlsberg</drink>
Attribute type="beer"
Text Carlsberg

Node 有个nodeValue属性,开始不知道和node的data属性有何差别,后来查了DOM的文档,如下解释:
XML 对象的节点值。如果 XML 对象是一个文本节点,则 nodeType 为 3,nodeValue 是节点的文本。如果 XML 对象是一个 XML 元素(nodeType 为 1),则 nodeValue 为 null 且只读

在Python里试了一下,对普通的文本节点,如“<server>mail.</server>”,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

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/wstarx/archive/2006/02/18/602104.aspx

===========

python如何读取xml文件

(2007-08-11 21:29:42)


转载


标签:

知识/探索

分类:语言学习
由于windows系统对于xml文件的默认格式是GB2312,而python对xml的格式要求是utf-8和utf-16,可是python的默认字体格式是ascii,因此,对于包含中文的xml文件,为了正确读取它,就得分两步完成:
1.将xml文件保存为utf-8格式,并将encoding改为utf-8,这样就可保证用IE打开xml文件的同时,python也可以打开此文件。
2.将python系统默认的字体编码模式改为gbk,这样就可以保证当python读取utf-8格式的xml文件时,将字体转化为gbk格式,python系统正确显示字体了。
3.将XML文件的字符串转化为gbk格式的str,系统就能使用该字符串进行各种操作了!
-================

对于刚刚接触Python的初学者来说,他们在学习的过程中会逐渐的发现这一编程语言实际上一款功能强大应用简单的计算机程序语言。我们今天将会为大家详细介绍一下有关Python读取XML文档的相关应用方式。

最近做一个小功能,里边包含Python读取XML文档的功能,封装了一个读取类,包括读取xml中所有数据,返回list集合;根据唯一节点值读取该节点及子节点的值

from xml.dom.minidom import parse,parseString
class XmlConfig:
def __init__(self,path):
selfself.xmlData=self.GetXml(path)
def GetText(self,nodelist):
r=""
for nxd in nd.childNodes:
rr=r+nxd.nodeValue
return r
##获取xml所有数据
def GetXml(self,path):
doc1=parse(path)
st=doc1.firstChild
websites= st.childNodes
lstList=[]
for sw in websites:
if sw.nodeType==sw.ELEMENT_NODE :
lsty=[]
for nd in sw.childNodes:
if nd.nodeType==nd.ELEMENT_NODE:
ndndName= nd.nodeName
ndndValue= nd.firstChild.data
b=(ndName,ndValue)
lsty.append(b)
lstList.append(lsty)
return lstList
##获取单个节点及子节点值
def GetSingle(self,siteName):
for item in self.xmlData:
for k,v in item:
if v==siteName:
return item
##获取单个节点及子节点值
def GetSingleDict(self,siteName):
lst=self.GetSingle(siteName)
dic1={}
if len(lst)>0:
for item in lst:
dic1[item[0]]=item[1]
return dic1

xml文档

< ?xml version="1.0" encoding="UTF-8"?>
< Site>
< WebSites>
< website>http://www.xxx.net< /website>
< loginurl>http:///www.xxx.net/login.php< /loginurl>
< username>uname=xxx< /username>
< passwd>pass=123456< /passwd>
< other>< ![CDATA[r=5&remember=0&ur=xxx]]>< /other>
< config>WebSite.ini< /config>
< configname>XXX< /configname>
< /WebSites>
< WebSites>
< website>http://www.xxx.com< /website>
< loginurl>http:///www.xxx.com/login.php< /loginurl>
< username>uname=xxx< /username>
< passwd>pass=123456< /passwd>
< other>< ![CDATA[r=5&remember=0&ur=xxx]]>< /other>
< config>WebSite.ini< /config>
< configname>XXX< /configname>
< /WebSites>
< /Site>

Python读取XML文档的调用:

if __name__=="__main__":

f=XmlConfig()

print f.xmlData

=============

博客园开博第一篇,奉上最近做的python读取xml文档的例子
最近做一个小功能,里边包含python读取xml配置文件的功能,封装了一个读取类,包括读取xml中所有数据,返回list集合;根据唯一节点值读取该节点及子节点的值




Code
1 from xml.dom.minidom import parse,parseString
2 class XmlConfig:
3     def __init__(self,path):
4         self.xmlData=self.GetXml(path)
5     def GetText(self,nodelist):
6         r=""
7         for nxd in nd.childNodes:
8             r=r+nxd.nodeValue
9         return r
10
11     ##获取xml所有数据
12     def GetXml(self,path):
13         doc1=parse(path)
14         st=doc1.firstChild
15         websites= st.childNodes
16
17         lstList=[]
18         for sw in websites:
19             if sw.nodeType==sw.ELEMENT_NODE :
20                 lsty=[]
21                 for nd in sw.childNodes:
22                     if nd.nodeType==nd.ELEMENT_NODE:
23                         ndName= nd.nodeName
24                         ndValue= nd.firstChild.data
25                         b=(ndName,ndValue)
26                         lsty.append(b)
27                 lstList.append(lsty)
28         return lstList
29
30     ##获取单个节点及子节点值
31     def GetSingle(self,siteName):
32         for item in self.xmlData:
33             for k,v in item:
34                 if v==siteName:
35                     return item
36
37     ##获取单个节点及子节点值
38     def GetSingleDict(self,siteName):
39         lst=self.GetSingle(siteName)
40         dic1={}
41         if len(lst)>0:
42             for item in lst:
43                 dic1[item[0]]=item[1]
44         return dic1


xml文档




Code
<?xml version="1.0" encoding="UTF-8"?>
<Site>
<WebSites>
<website>http://www.xxx.net</website>
<loginurl>http:///www.xxx.net/login.php</loginurl>
<username>uname=xxx</username>
<passwd>pass=123456</passwd>
<other><![CDATA[r=5&remember=0&ur=xxx]]></other>
<config>WebSite.ini</config>
<configname>XXX</configname>
</WebSites>
<WebSites>
<website>http://www.xxx.com</website>
<loginurl>http:///www.xxx.com/login.php</loginurl>
<username>uname=xxx</username>
<passwd>pass=123456</passwd>
<other><![CDATA[r=5&remember=0&ur=xxx]]></other>
<config>WebSite.ini</config>
<configname>XXX</configname>
</WebSites>
</Site>

调用

if __name__=="__main__":
f=XmlConfig()
print f.xmlData
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: