python 讀取xml文件


首先,獲得標簽信息abc.xml

<?xml version="1.0" encoding="utf-8"?>
<catalog>
    <maxid>4</maxid>
    <login username="pytest" password="123456">
        <caption>Python</caption>
        <item id="4">
            <caption>Testing</caption>
        </item>
    </login>
    <item id="2">
        <caption>Zope</caption>
    </item>

</catalog>

python獲取catalog標簽的信息

# -*- coding:utf-8 -*-

import xml.dom.minidom

# 打開xml文檔
dom = xml.dom.minidom.parse('abc.xml')

# 得到文檔元素對象
root = dom.documentElement
    print root.nodeName
    print root.nodeValue
    print root.nodeType
    print root.ELEMENT_NODE

xml.dom.minidom 模塊被用來處理xml文件

parse():用於打開一個xml文件

documentElement:用於得到dom對象的文檔元素,並將獲得的對象給root,每一個結點都有它的nodeName,nodeValue,nodeType屬性

nodeName:結點名字

nodeValue:結點值,只對文本結點有效

nodeType:結點類型

二、獲得子標簽:

<maxid>
<login>
import xml.dom.minidom

dom = xml.dom.minidom.parse('abc.xml')

root = dom.documentElement

bb = root.getElementsByTagName('maxid')
bb = bb[0]
print bb.nodeName

bb = root.getElementsByTagName('login')
bb = bb[0]
print bb.nodeName

三、區分相同標簽名字的標簽

<caption>
<item>
import xml.dom.minidom

# 打開xml文檔
dom = xml.dom.minidom.parse('abc.xml')

# 得到文檔元素對象
root = dom.documentElement

aa = root.getElementsByTagName('caption')
a = aa[2]
print a.nodeName

aa = root.getElementsByTagName('item')
a = aa[1]
print a.nodeName

root.getElementsByTagName('caption')獲得的標簽是caption一組標簽

四、獲得標簽的屬性值

username="pytest" password="123456"
id="4"
id="2"
import xml.dom.minidom

# 打開xml文檔
dom = xml.dom.minidom.parse('abc.xml')

# 得到文檔元素對象
root = dom.documentElement

#  獲取標簽的屬性值
itemlist = root.getElementsByTagName('login')
item = itemlist[0]
un = item.getAttribute('username')
print un

pd = item.getAttribute('password')
print pd

ii = root.getElementsByTagName('item')
i1 = ii[0]
i = i1.getAttribute('id')
print i

i2 = ii[1]
i = i2.getAttribute('id')
print i

五、獲得標簽對之間的數據

 <caption>Python</caption>
 <caption>Testing</caption>
<caption>Zope</caption>
import xml.dom.minidom

# 打開xml文檔
dom = xml.dom.minidom.parse('abc.xml')

# 得到文檔元素對象
root = dom.documentElement

cc = dom.getElementsByTagName('caption')
c1 = cc[0]
print c1.firstChild.data

c2 = cc[1]
print c2.firstChild.data

c3 = cc[2]
print c3.firstChild.data

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM