Python解析xml檔案

2021-09-11 21:06:13 字數 2190 閱讀 8557

<?xml version="1.0" encoding="utf-8"?>

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 boredom

python中用xml.dom.minidom來解析xml檔案,例項如下:

#!/usr/bin/python 

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

from xml.dom.minidom import parse

import xml.dom.minidom

# 使用minidom解析器開啟 xml 文件

domtree = xml.dom.minidom.parse("movies.xml")

collection = domtree.documentelement

if collection.hasattribute("shelf"):

print "root element : %s" % collection.getattribute("shelf")

# 在集合中獲取所有電影

movies = collection.getelementsbytagname("movie")

# 列印每部電影的詳細資訊

for movie in movies:

print "*****movie*****"

if movie.hasattribute("title"):

print "title: %s" % movie.getattribute("title")

type = movie.getelementsbytagname('type')[0]

print "type: %s" % type.childnodes[0].data

format = movie.getelementsbytagname('format')[0]

print "format: %s" % format.childnodes[0].data

rating = movie.getelementsbytagname('rating')[0]

print "rating: %s" % rating.childnodes[0].data

description = movie.getelementsbytagname('description')[0]

print "description: %s" % description.childnodes[0].data

以上程式執行結果如下:

root element : new arrivals 

*****movie*****

title: enemy behind

type: war, thriller

format: *** rating: pg

description: talk about a us-japan war

*****movie*****

title: transformers

type: *****, science fiction

format: *** rating: r

description: a schientific fiction

*****movie*****

title: trigun

type: *****, action

format: *** rating: pg

description: vash the stampede!

*****movie*****

title: ishtar

type: comedy

format: vhs

rating: pg

description: viewable boredom

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...

Python 解析XML檔案

python檔案 複製 如下 par ml.py 本例子參考自python聯機文件,做了適當改動和新增 import xml.parsers.expat 控制列印縮排 level 0 獲取某節點名稱及屬性值集合 def start element name,attrs global level pr...