Python解析xml檔案(二)

2021-07-16 09:00:18 字數 2855 閱讀 3633

獲取標籤之間的資料值:

movie 節點,***format是乙個文字節點

war, thriller

***2003

pg10

talk about a us-japan war

*****, science fiction

***1989r8

a schientific fiction

*****, action

***4pg

10vash the stampede!

comedy

vhspg2

viewable boredom

分析整個xml檔案:

#coding=utf-8

import xml.dom.minidom

#讀取xml檔案

dom = xml.dom.minidom.parse("a.xml")

root = dom.documentelement

#獲取節點的名字

print root.nodename

#獲取節點的值

print root.nodevalue

#獲取節點的型別

print root.nodetype

print root.element_node

#獲取子節點,如果有多個,將以陣列的形式儲存到變數中

childs = root.getelementsbytagname('movie')

print '*****===childs*****==='

print 'childs: %s' % childs.length

for child in childs:

#獲取節點的屬性值

print child.getattribute('title')

grandsuns = child.getelementsbytagname('type')

for grandsun in grandsuns:

print "*****grandsun*****==="

print grandsun.nodename

#獲取節點的資料值,標籤之間的值

print grandsun.firstchild.data

以上這些實現分析,該方法在解析乙個xml檔案的時候,會將整個xml檔案讀入到記憶體中,形成乙個element樹,之後就可以通過使用不同的方法獲取該樹內的任意節點以及節點的屬性和節點的值。通過
getelementsbytagname可以獲取節點的子節點,每個節點的子節點可能含有不止乙個的子節點,這樣搜尋結果返回的將是乙個列表,可以根據陣列的使用原則訪問所有的返回節點。
firstchild 

屬性返回被選節點的第乙個子節點

,.data

表示獲取該節點人資料。理解:

vhs

comedy

1234556pg2

viewable boredom

以上這個xml如果檢視type的資料值,使用

firstchild得到的就是

vhs獲取其data時就是乙個空的。
第二種方式:該方法主要用於遍歷某乙個節點下的所有子節點

#coding=utf-8

from xml.etree import elementtree as et

per=et.parse('a.xml')

p=per.findall('./movie/year')

print p

for x in p:

print x.text

print x.tag

p = per.findall('./movie/type')

for x in p:

print x.text

findall用於指定在哪一級標籤下開始遍歷。

getchildren方法按照文件順序返回所有子標籤。並輸出標籤名(

child.tag

)和標籤的資料(

Python解析xml檔案

war,thriller 2003 pg10 talk about a us japan war science fiction 1989r8 a schientific fiction action 4 pg10 vash the stampede comedy vhspg 2viewable b...

Python解析xml檔案

解析 xml 格式的檔案有多種方法,這裡只介紹使用 xml.etree.elementtree 這種解析方式.elementtree在 python 標準庫中有兩種實現。一種是純 python 實現例如 xml.etree.elementtree 另外一種是速度快一點的 xml.etree.cele...

python 解析xml檔案

et.parser 用法 python3 xml解析模組xml.etree.elementtree簡介 刪除重複xml節點 import xml.etree.elementtree as et 匯入xml模組 root et.parse gho.xml 分析指定xml檔案 tree root.get...