xml檔案內容如下:
<?xml version="1.0" encoding="utf-8"?>
>
>
4maxid
>
username
="pytest"
passwd
='123456'
>
>
pythoncaption
>
"4">
>
測試caption
>
item
>
login
>
"2">
>
zopecaption
>
item
>
catalog
>
輸出import xml.dom.minidom
#開啟xml文件
dom = xml.dom.minidom.parse(
'abc.xml'
)#得到文件元素物件
root = dom.documentelement
(root.nodename)
(root.nodevalue)
(root.nodetype)
(root.element_node)
mxl.dom.minidom 模組被用來處理xml檔案,所以要先引入。catalog
none
11
xml.dom.minidom.parse() 用於開啟乙個xml檔案,並將這個檔案物件dom變數。
documentelement 用於得到dom物件的文件元素,並把獲得的物件給root
每乙個結點都有它的nodename,nodevalue,nodetype屬性。
nodename為結點名字。
nodevalue是結點的值,只對文字結點有效。
nodetype是結點的型別。catalog是element_node型別
import xml.dom.minidom
#開啟xml文件
dom = xml.dom.minidom.parse(
'abc.xml'
)#得到文件元素物件
root = dom.documentelement
id= root.getelementsbytagname(
'maxid')[
0]print(id
.nodename)
輸出maxid
如何區分相同標籤名字的標籤:
例如b=root.getelementsbytagname(『caption』) 獲得的是標籤為caption 一組標籤,b[0]表示一組標籤中的第乙個;b[2]表示這一組標籤中的第三個。
例如和
標籤是有屬性的,如何獲得他們的屬性?
getattribute方法可以獲得元素的屬性所對應的值。
import xml.dom.minidom
#開啟xml文件
dom = xml.dom.minidom.parse(
'abc.xml'
)#得到文件元素物件
root = dom.documentelement
id= root.getelementsbytagname(
'maxid')[
0]print(id
.nodename)
user=root.getelementsbytagname(
'login')[
0]name=user.getattribute(
"username"
(name)
輸出pytest
firstchild 屬性返回被選節點的第乙個子節點,.data表示獲取該節點人資料。
import xml.dom.minidom
#開啟xml文件
dom = xml.dom.minidom.parse(
'abc.xml'
)#得到文件元素物件
root = dom.documentelement
cap=root.getelementsbytagname(
'caption')[
0]cap=cap.firstchild.data
(cap)
輸出python
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...