首先,我先給出一段xml文件:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
"liechtenstein">
"yes">2
2008
141100
"austria" direction = "e"
/>
"switzerland" direction = "w"
/>
"singapore">
"yes">5
2011
59900
"malaysia" direction="n"
/>
"panama">
"yes">69
2011
13600
"costa rica" direction="w"
/>
"colombia" direction="e"
/>
data>
然後,用python中的xml模組對上面的xml文字進行操作:
# author : xuefeng
# 傳統的系統介面多使用xml
import xml.etree.elementtree as et
tree = et.parse(
"xml_t.xml"
)root = tree.getroot(
)print
(root)
print
(root.tag)
# 遍歷xml文件
# tag---------->標籤名
# attrib------->屬性
# text--------->文字資訊
for child in root:
print
(child.tag, child.attrib)
for i in child:
print
(i.tag, i.text, i.attrib)
# 只遍歷year的文字資訊
for node in root.
iter
('year'):
print
(node.attrib, node.text)
# 修改xml檔案
for node in root.
iter
("year"):
nyear =
int(node.text)+1
node.text =
str(nyear)
node.
set(
"updated"
,"yes"
)tree.write(
'xml_t.xml'
)# 刪除節點
for country in root.findall(
'country'):
rank =
int(country.find(
'rank'
).text)
if rank >50:
root.remove(country)
tree.write(
'output.xml'
)# 建立xml檔案
new_xml = et.element(
'namelist'
)name = et.subelement(new_xml,
"name"
, attrib=
)age = et.subelement(name,
"age"
, attrib=
)*** = et.subelement(name,
"***"
)***.text =
'33'
name2 = et.subelement(new_xml,
"name"
, attrib=
)age = et.subelement(name2,
"age"
)age.text =
'19'
et = et.elementtree(new_xml)
et.write(
"test.xml"
, encoding=
"utf-8"
, xml_declaration=
true
)et.dump(new_xml)
用Python對MySQL簡單操作
import pymysql 連線資料庫 conn pymysql.connect host localhost user root password helloguitar532123 charset utf8 獲得浮標 cursor conn.cursor 建立資料庫 sql create cr...
用Python解決x的n次方問題
我考慮到了x的所有n次的情況,下面的 有可能是不完美的,但是肯定是對的。def aaa x,n a is程式設計客棧instance x,int,float 這是考慮x和n的型別,需要滿足條件才可以 if a true 往下執行 return none b isinstance n,int,floa...
用Python對XML讀取和處理
簡介 xml不是為了方便閱讀而設計,而是為了編碼為資料。當有一些文字有很多文件,可以用編碼的方式使3一些文字便與處理。設計原則def get author root authors for author in root.findall fm bibl aug au 用這種方法就可以建立字典 data...