xml是實現不同語言或程式之間進行資料交換的協議,跟json差不多,但json使用起來更簡單,不過,古時候,在json還沒誕生的黑暗年代,大家只能選擇用xml,至今很多傳統公司如金融行業的很多系統的介面還主要是xml。
xml_test
<?xml version=
"1.0"?>
"liechtenstein"
>
"yes"
>
2<
/rank>
2008
<
/year>
141100
<
/g***c>
"austria" direction=
"e"/
>
"switzerland" direction=
"w"/
>
<
/country>
"singapore"
>
"yes"
>
5<
/rank>
2011
<
/year>
59900
<
/g***c>
"malaysia" direction=
"n"/
>
<
/country>
"panama"
>
"yes"
>
69<
/rank>
2011
<
/year>
13600
<
/g***c>
"costa rica" direction=
"w"/
>
"colombia" direction=
"e"/
>
<
/country>
<
/data>
import xml.etree.elementtree as et
tree = et.parse(
"xml_test"
)root = tree.getroot(
)print
(root.tag)
#data 根
# 遍歷xml文件
for child in root:
print
(child.tag, child.attrib)
for i in child:
print
(i.tag, i.text)
# 只遍歷year 節點
for node in root.
iter
('year'):
print
(node.tag, node.text)
# 修改
for node in root.
iter
('year'):
new_year =
int(node.text)+1
node.text =
str(new_year)
node.
set(
"updated"
,"yes"
)tree.write(
"xml_test_2"
)# 刪除node
for country in root.findall(
'country'):
rank =
int(country.find(
'rank'
).text)
if rank >50:
root.remove(country)
tree.write(
'xml_test_3'
)
xml_test_2
"liechtenstein"
>
"yes"
>
2<
/rank>
"yes"
>
2009
<
/year>
141100
<
/g***c>
"e" name=
"austria"
/>
"w" name=
"switzerland"
/>
<
/country>
"singapore"
>
"yes"
>
5<
/rank>
"yes"
>
2012
<
/year>
59900
<
/g***c>
"n" name=
"malaysia"
/>
<
/country>
"panama"
>
"yes"
>
69<
/rank>
"yes"
>
2012
<
/year>
13600
<
/g***c>
"w" name=
"costa rica"
/>
"e" name=
"colombia"
/>
<
/country>
<
/data>
xml_test_3
"liechtenstein"
>
"yes"
>
2<
/rank>
2008
<
/year>
141100
<
/g***c>
"e" name=
"austria"
/>
"w" name=
"switzerland"
/>
<
/country>
"singapore"
>
"yes"
>
5<
/rank>
2011
<
/year>
59900
<
/g***c>
"n" name=
"malaysia"
/>
<
/country>
<
/data>
python常用模組 XML模組
乙個簡單的xml檔案 xml模組常用函式 xml 指可擴充套件標記語言 extensible markup language xml 被設計用來傳輸和儲存資料。xml 是一套定義語義標記的規則,這些標記將文件分成許多部件並對這些部件加以標識。它也是元標記語言,即定義了用於定義其他與特定領域有關的 語...
Python內建模組 xml模組
處理文件 import xml.etree.elementtree as ettree et.parse xmlfile et.parse 解析xml文件 root tree.getroot 獲取根節點 print root.tag root.tag 獲取根節點標籤 這裡是data print i....
python內建模組之XML模組
xml和json 一樣都是可以跨平台的,只是xml相比較,老一點 import xml.etree.elementtree as et a et.parse first xml.xml 載入乙個檔案 root a.getroot print root 乙個xml檔案 print root.tag x...