關於XML 的起源和發展

參考:XML

XML 學習

參考: XML 學習

使用Python ElementTree 解析XML 例項

這是一個例子,本文將基於這個xml 檔案進行處理

no=

“2009081097”

>

nickname=

“apple”

>

jack

M

updated=

“yes”

>

89

subject=

“math”

>

97

subject=

“chinese”

>

90

no=

“2009081098”

>

nickname=

“apple”

>

sunny

W

updated=

“yes”

>

90

subject=

“math”

>

87

subject=

“chinese”

>

96

no=

“2009081099”

>

nickname=

“apple”

>

Anna

M

updated=

“yes”

>

88

subject=

“math”

>

64

subject=

“chinese”

>

98

在做處理之前,要清楚xml 檔案基本要處理的內容是下面的幾個:

節點: jack 就是一個節點,根節點就是最外面那個節點,比如這裡的。

屬性:nickname 是元素的屬性attrib。獲取用get, 設定用set。

文字內容:jack 是元素的text。讀內容用。text。

接下來用程式碼來解釋相關的操作:

‘’‘

ElementTree 生來就是為了處理 XML ,它在 Python 標準庫中有兩種實現。一種是純 Python 實現例如 xml。etree。ElementTree ,另外一種是速度快一點的 xml。etree。cElementTree 。你要記住: 儘量使用 C 語言實現的那種,因為它速度更快,而且消耗的記憶體更少。

一般使用下面的程式碼來匯入。

’‘’

try

import

xml。etree。cElementTree

as

et

except

ImportError

import

xml。etree。ElementTree

as

et

# 解析檔案

parser

=

et

parse

“data。xml”

# 獲取根節點

root

=

parser

getroot

()

# 獲取標籤名字

print

root

tag

# 獲取屬性

attr

=

root

attrib

# 透過索引訪問節點

print

root

0

][

0

text

# 查詢根目錄下面的子元素

for

name

in

root

findall

“student”

):

# 查詢一個具體的元素

print

name

find

“age”

get

“updated”

))

#獲取屬性

print

name

get

“no”

))

#獲取student元素

#更改student。age年齡

#獲取name設定屬性

#寫入文件

for

child

in

root

iter

“student”

):

new_age

=

int

child

find

“age”

text

+

10

child

find

“age”

text

=

str

new_age

child

find

“name”

set

“nickname”

“apple”

parser

write

“data。xml”

#查詢根目錄下面的子元素

#查詢age

#如果大於age刪除元素

#寫入文件

for

offspring

in

root

findall

“student”

):

age

=

int

offspring

find

“age”

text

if

age

>

60

):

root

remove

offspring

parser

write

“data。xml”

#建立元素

father

=

et

Element

“father”

father

text

=

“Jason”

son

=

et

SubElement

father

“son”

son

text

=

“Lan”

daughter

=

et

SubElement

father

“daughter”

daughter

text

=

“sunny”

print

et

dump

father

))

exit

()

#迭代屬性

for

child

in

root

print

((

“iterator node name is {} , attr is {}”

format

)(

child

tag

child

attrib

for

student

in

root

findall

‘student’

):

id

=

student

get

“no”

name

=

student

find

“name”

text

print

id

name

for

age

in

root

iter

‘age’

):

new_age

=

int

age

text

+

1

age

text

=

str

new_age

age

set

‘updated’

‘yes’

#寫入檔案 用什麼編碼 是否要申明頭部檔案

parser

write

“data。xml”

encoding

=

“utf-8”

xml_declaration

=

True

for

name

in

root

iter

“student”

):

#print name。tag

print

name

attrib

“no”

])