python獲取xml文件信息


1、xml文件,文件名info.xml,具體內容如下:

<?xml version="1.0" encoding="utf-8"?>
<info>
    <base>
        <platform>Windows</platform>
        <browser>Chrome</browser>
        <url>http://www.baidu.com</url>
        <login username="admin" password="123456" />
        <login username="guest" password="654321" />
    </base>
    <test>
        <province>北京</province>
        <province>廣東</province>
        <province>浙江</province>
            <city>深圳</city>
            <city>珠江</city>
            <city>杭州</city>
    </test>
</info>

2、使用python程序獲取xml信息,具體代碼如下:

 1 """xml獲取任意標簽名與屬性名,標簽之間數據"""
 2 import os
 3 from xml.dom import minidom
 4 
 5 # 當前文件路徑
 6 DirBase = os.path.abspath(os.path.dirname(__file__))
 7 # xml文件絕對路徑
 8 file_path = DirBase + '\\info.xml'
 9 # 打開xml文件
10 dom = minidom.parse(file_path)
11 # 得到元素對象
12 root = dom.documentElement
13 
14 # 獲取標簽名
15 logins = root.getElementsByTagName('platform')
16 tag = logins[0].tagName
17 print(tag)  # >>platform
18 
19 # 獲取屬性名
20 logins = root.getElementsByTagName('login')
21 tag_name = logins[0].getAttribute('username')
22 print(tag_name)  # >>admin
23 tag_name = logins[0].getAttribute('password')
24 print(tag_name)  # >>123456
25 
26 # 標簽之間的數據
27 msg = root.getElementsByTagName('city')
28 prs = msg[0].firstChild.data
29 print(prs)  # >>深圳
30 prs = msg[1].firstChild.data
31 print(prs)  # >>珠江
32 prs = msg[2].firstChild.data
33 print(prs)  # >>杭州


免責聲明!

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



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