python 讀取xml的方法

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集合;根據唯一節點值讀取該節點及子節點的值

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

xml文檔

  1. < ?xml version="1.0" encoding="UTF-8"?> 
  2. < Site> 
  3. < WebSites> 
  4. < website>http://www.xxx.net< /website> 
  5. < loginurl>http:///www.xxx.net/login.php< /loginurl> 
  6. < username>uname=xxx< /username> 
  7. < passwd>pass=123456< /passwd> 
  8. < other>< ![CDATA[r=5&remember=0&ur=xxx]]>< /other> 
  9. < config>WebSite.ini< /config> 
  10. < configname>XXX< /configname> 
  11. < /WebSites> 
  12. < WebSites> 
  13. < website>http://www.xxx.com< /website> 
  14. < loginurl>http:///www.xxx.com/login.php< /loginurl> 
  15. < username>uname=xxx< /username> 
  16. < passwd>pass=123456< /passwd> 
  17. < other>< ![CDATA[r=5&remember=0&ur=xxx]]>< /other> 
  18. < config>WebSite.ini< /config> 
  19. < configname>XXX< /configname> 
  20. < /WebSites> 
  21. < /Site> 

Python讀取XML文檔的調用:

  1. if __name__=="__main__":  
  2. f=XmlConfig()  
  3. print f.xmlData
=============
博客園開博第一篇,奉上最近做的python讀取xml文檔的例子
最近做一個小功能,裏邊包含python讀取xml配置文件的功能,封裝了一個讀取類,包括讀取xml中所有數據,返回list集合;根據唯一節點值讀取該節點及子節點的值

 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文檔

<?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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章