python基礎(chǔ)之xml處理

xml查詢處理

# -*- coding:utf-8 -*-
# Author:chinablue

# tag text attrib

import xml.etree.ElementTree as ET

tree = ET.parse("xmlabc")
root = tree.getroot()

# print root
# print root.tag
#
# # 遍歷xml整個文檔
# for child in root:
#     print child.tag,child.attrib
#     for i in child:
#         print i.tag,i.text

# 只遍歷某個節(jié)點
for node in root.iter('age'):
    print node.tag,node.text

xml修改處理

# -*- coding:utf-8 -*-
# Author:chinablue

# tag text attrib

import xml.etree.ElementTree as ET

tree = ET.parse("xmlabc")
root = tree.getroot()

# 修改age
for node in root.iter('age'):
    new_age = int(node.text) + 1
    node.text = str(new_age)
    node.set("updated","yes")

tree.write("xmlabc_modify.xml")

xml 刪除處理

# -*- coding:utf-8 -*-
# Author:chinablue

# tag text attrib

import xml.etree.ElementTree as ET

tree = ET.parse("xmlabc")
root = tree.getroot()


# 刪除node
for country in root.findall('country'):
    rank = int(country.find('rank').text)
    if rank > 50:
        root.remove(country)
tree.write("output.xml")

xml 創(chuàng)建處理

# -*- coding:utf-8 -*-
# Author:chinablue

# tag text attrib

import xml.etree.ElementTree as ET

new_xml = ET.Element('namelist')
name = ET.SubElement(new_xml,"name",attrib={'enrolled':'yes'})
age = ET.SubElement(name,"age",attrib={'checked':'no'})
sex = ET.SubElement(name,"sex")

age.text = '23'

name2 = ET.SubElement(new_xml,"name",attrib={'enrolled':'yes'})
age = ET.SubElement(name2,"age",attrib={'checked':'no'})
age.text = '33'

# 生成文檔對象
et = ET.ElementTree(new_xml)
et.write("create.xml",encoding="utf-8",xml_declaration=True)
ET.dump(new_xml)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評論 19 139
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,727評論 18 399
  • 1. 簡介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存儲過程以及高級映射的優(yōu)秀的...
    笨鳥慢飛閱讀 6,248評論 0 4
  • 【資訊導讀】 賴氨酸價格大漲行業(yè)龍頭受益 國內(nèi)最大充電設(shè)備展開幕智能充電受關(guān)注 科士達加大海外市場開拓力度 英唐智...
    72e31abbfa15閱讀 278評論 0 0
  • by孤鳥差魚 你還真信 我的誠懇 沒有摻假
    孤鳥差魚閱讀 218評論 0 2

友情鏈接更多精彩內(nèi)容