python--xml模組

來源:互聯網
上載者:User

標籤:ted   bsp   imp   date   檔案的   root   app   remove   另一個   

#==========================================>查
import xml.etree.ElementTree as ET        #導包,重新命名
# tree=ET.parse(‘a.xml‘)         #將a.xml檔案解析成一棵樹
# root=tree.getroot()   #得到根節點


#三種尋找節點的方式
# res=root.iter(‘rank‘)    # iter會在整個樹中進行尋找,而且是尋找到所有
# for item in res:
# # print(item)
# print(‘=‘*50)
# print(item.tag)   # 標籤名
# print(item.attrib)   #屬性
# print(item.text)   #常值內容


# res=root.find(‘country‘)   # find只能在當前元素的下一級開始尋找。並且只找到一個就結束
# print(res.tag)
# print(res.attrib)
# print(res.text)
# nh=res.find(‘neighbor‘)
# print(nh.attrib)


# cy=root.findall(‘country‘)   # findall只能在當前元素的下一級開始尋找,但是會去找所有的
# print([item.attrib for item in cy])

xml檔案的幾種操作:改,增,刪

#==========================================>改
# import xml.etree.ElementTree as ET
# tree=ET.parse(‘a.xml‘)
# root=tree.getroot()
#
# for year in root.iter(‘year‘):
# year.text=str(int(year.text) + 10)
# year.attrib={‘updated‘:‘yes‘}
#
# # tree.write(‘b.xml‘)   #寫到另一個檔案裡
# tree.write(‘a.xml‘)

 

#==========================================>增
import xml.etree.ElementTree as ET
tree=ET.parse(‘a.xml‘)
root=tree.getroot()

for country in root.iter(‘country‘):
# print(country)
year=country.find(‘year‘)
# print(year)
if int(year.text) > 2020:
# print(country.attrib)
# ele=ET.Element(‘Mr.Haigui‘)   #設定標籤
# ele.attrib={‘nb‘:‘yes‘}    #設定屬性
# ele.text=‘非常帥‘    #設定常值內容
# country.append(ele)    #增加操作
country.remove(year)    #刪除操作
tree.write(‘b.xml‘)

python--xml模組

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.