python使用ElementTree操作xml

前言:

在web數(shù)據(jù)傳輸過程中印叁,用到最多的兩種數(shù)據(jù)傳輸格式分別是json和xml丁侄,現(xiàn)記錄一下如何使用python的ElementTree庫來操作xml,實現(xiàn)對xml的增刪查改!

說明:

這里通過以下方式來操作xml

  • 標(biāo)簽節(jié)點的CRUD
  • 標(biāo)簽屬性的CRUD
  • 標(biāo)簽值的CRUD
xml數(shù)據(jù)樣例:
<?xml version='1.0' encoding='utf-8'?>
<root name="test" msg="測試">
    <head>
        <uid>6taE112M48343D7QaP452o29</uid>
        <fileType>Other</fileType>
        <sum>100</sum>
        <createTime>2018-11-28 15:10:02</createTime>
    </head>
    <datas>
        <data>
            <id>1530</id>
            <osId>UNIX1001</osId>
            <ip>192.168.1.2</ip>
            <groupId>275</groupId>
            <secrity>安全</secrity>
            <securityManager>張三</securityManager>
            <port>22</port>
            <protocol>ssh</protocol>
            <upPriv>su -</upPriv>
        </data>
        <data>
            <id>1531</id>
            <osId>UNIX1002</osId>
            <ip>192.168.1.3</ip>
            <groupId>276</groupId>
            <secrity>安全</secrity>
            <securityManager>李四</securityManager>
            <port>25</port>
            <protocol>ssh</protocol>
            <upPriv>insert</upPriv>
        </data>
    </datas>
</root>
標(biāo)簽節(jié)點的CRUD
1.查詢標(biāo)簽節(jié)點

1.findall(標(biāo)簽名):查找所有標(biāo)簽節(jié)點失尖,返回一個可迭代對象
2.find(標(biāo)簽名):查找滿足條件的第一個標(biāo)簽節(jié)點,返回該節(jié)點對象

#coding:utf-8
try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET

def select_node():
    """查詢節(jié)點"""
    xml_path = "test.xml"
    # 通過獲取tree對象
    tree = ET.parse(xml_path)
    # 獲取根節(jié)點
    root = tree.getroot()

    # findall():查找并迭代標(biāo)簽
    for data in root.findall('.//data'):  # xpath語法
        print data
    # find(): 查找滿足條件的第一個標(biāo)簽
    data = root.find('.//data')
    print data
2.刪除標(biāo)簽節(jié)點

1.remove(節(jié)點對象):刪除指定的節(jié)點
2.clear():清空本節(jié)點下的所有子節(jié)點

# coding:utf-8

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET


def del_node():
    """添加節(jié)點"""
    xml_path = "test.xml"
    # 通過獲取tree對象
    tree = ET.parse(xml_path)
    # 獲取根節(jié)點
    root = tree.getroot()
    # 獲取datas節(jié)點
    datas_node = root.find(".//datas")
    # 獲取datas的第一個子節(jié)點
    data_node = root.find('.//datas/data')
    # 1.remove(節(jié)點對象):刪除指定的節(jié)點
    datas_node.remove(data_node)
    # 2.clear(): 清空datas下的所有子節(jié)點
    # datas_node.clear()
    # 回寫xml數(shù)據(jù)
    tree.write("test2.xml", encoding='utf-8', xml_declaration=True)
3.添加標(biāo)簽節(jié)點:(需要兩步:創(chuàng)建標(biāo)簽節(jié)點,添加標(biāo)簽)

1.創(chuàng)建標(biāo)簽節(jié)點:
Element(標(biāo)簽名):創(chuàng)建標(biāo)簽節(jié)點對象
2.添加標(biāo)簽:
1.append(標(biāo)簽節(jié)點):在標(biāo)簽的末尾添加新標(biāo)簽
2.insert(索引號砾肺,標(biāo)簽節(jié)點):在指定的索引位置添加新標(biāo)簽

# coding:utf-8

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET


def add_node():
    xml_path = "test.xml"
    # 通過獲取tree對象
    tree = ET.parse(xml_path)
    # 獲取根節(jié)點
    root = tree.getroot()
    # Element(標(biāo)簽名):創(chuàng)建標(biāo)簽節(jié)點對象
    new_node = ET.Element("node")
    # 添加標(biāo)簽值
    new_node.text = "newNode"
    # 添加標(biāo)簽
    root.append(new_node)
    # 回寫xml數(shù)據(jù)
    tree.write("test2.xml", encoding='utf-8', xml_declaration=True)
標(biāo)簽屬性的CRUD
1.獲取標(biāo)簽屬性:

1.attrib:以字典形式返回標(biāo)簽屬性
2.keys():返回標(biāo)簽屬性名稱列表
3.items():返回標(biāo)簽屬性項列表
4.get(key, default=None):根據(jù)標(biāo)簽屬性名稱獲取標(biāo)簽屬性值

# coding:utf-8
try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET

def select_attrib():
    """查詢標(biāo)簽屬性"""
    xml_path = "test.xml"
    # 通過獲取tree對象
    tree = ET.parse(xml_path)
    # 獲取根節(jié)點
    root = tree.getroot()
    # 獲取標(biāo)簽屬性
    attr_dict = root.attrib  # {'msg': '測試', 'name': 'test'}
    attr_key = root.keys()  # ['msg', 'name']
    attr_item = root.items()  # [('msg', u'測試'), ('name', 'test')]
    attr_get = root.get('name')  # test
2.添加/修改標(biāo)簽屬性:

set(key, value):添加/修改標(biāo)簽屬性

# coding:utf-8

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET


def update_attrib():
    """添加/修改標(biāo)簽屬性"""
    xml_path = "test.xml"
    # 通過獲取tree對象
    tree = ET.parse(xml_path)
    # 獲取根節(jié)點
    root = tree.getroot()
    # 不存在則添加
    root.set("age", "30")
    # 存在則修改
    root.set("name", "mytest")
    # 回寫xml數(shù)據(jù)
    tree.write("test2.xml", encoding='utf-8', xml_declaration=True)
3.刪除標(biāo)簽屬性:

del node.attrib[key]

# coding:utf-8
try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET

def del_attrib():
    """刪除節(jié)點屬性"""
    xml_path = "test.xml"
    # 通過獲取tree對象
    tree = ET.parse(xml_path)
    # 獲取根節(jié)點
    root = tree.getroot()
    # 刪除名為name的屬性
    del root.attrib["name"]
    # 回寫xml數(shù)據(jù)
    tree.write("test2.xml", encoding='utf-8', xml_declaration=True)
標(biāo)簽值的CRUD
1.獲取標(biāo)簽值

node.text

# coding:utf-8

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET

def select_node_value():
    """查詢節(jié)點值"""
    xml_path = "test.xml"
    # 通過獲取tree對象
    tree = ET.parse(xml_path)
    # 獲取根節(jié)點
    root = tree.getroot()
    # 獲取第一個ip節(jié)點
    ip_node = root.find(".//ip")
    # 獲取節(jié)點值
    node_value = ip_node.text
    print node_value
2.添加/修改標(biāo)簽值

node.text = value :存在就修改,不存在就添加

# coding:utf-8
try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET

def update_node_value():
    """添加/修改標(biāo)簽屬性"""
    xml_path = "test.xml"
    # 通過獲取tree對象
    tree = ET.parse(xml_path)
    # 獲取根節(jié)點
    root = tree.getroot()
    # 獲取第一個ip節(jié)點
    ip_node = root.find(".//ip")
    # 修改節(jié)點值
    ip_node.text = "10.1.1.1"
    # 回寫xml數(shù)據(jù)
    tree.write("test2.xml", encoding='utf-8', xml_declaration=True)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末防嗡,一起剝皮案震驚了整個濱河市变汪,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌本鸣,老刑警劉巖疫衩,帶你破解...
    沈念sama閱讀 216,372評論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡闷煤,警方通過查閱死者的電腦和手機(jī)童芹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來鲤拿,“玉大人假褪,你說我怎么就攤上這事〗辏” “怎么了生音?”我有些...
    開封第一講書人閱讀 162,415評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長窒升。 經(jīng)常有香客問我缀遍,道長,這世上最難降的妖魔是什么饱须? 我笑而不...
    開封第一講書人閱讀 58,157評論 1 292
  • 正文 為了忘掉前任域醇,我火速辦了婚禮,結(jié)果婚禮上蓉媳,老公的妹妹穿的比我還像新娘譬挚。我一直安慰自己,他們只是感情好酪呻,可當(dāng)我...
    茶點故事閱讀 67,171評論 6 388
  • 文/花漫 我一把揭開白布减宣。 她就那樣靜靜地躺著,像睡著了一般玩荠。 火紅的嫁衣襯著肌膚如雪漆腌。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,125評論 1 297
  • 那天姨蟋,我揣著相機(jī)與錄音屉凯,去河邊找鬼。 笑死眼溶,一個胖子當(dāng)著我的面吹牛悠砚,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播堂飞,決...
    沈念sama閱讀 40,028評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼灌旧,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了绰筛?” 一聲冷哼從身側(cè)響起枢泰,我...
    開封第一講書人閱讀 38,887評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎铝噩,沒想到半個月后衡蚂,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,310評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,533評論 2 332
  • 正文 我和宋清朗相戀三年毛甲,在試婚紗的時候發(fā)現(xiàn)自己被綠了年叮。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,690評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡玻募,死狀恐怖只损,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情七咧,我是刑警寧澤跃惫,帶...
    沈念sama閱讀 35,411評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站艾栋,受9級特大地震影響爆存,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜蝗砾,卻給世界環(huán)境...
    茶點故事閱讀 41,004評論 3 325
  • 文/蒙蒙 一终蒂、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧遥诉,春花似錦、人聲如沸噪叙。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽睁蕾。三九已至苞笨,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間子眶,已是汗流浹背瀑凝。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評論 1 268
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留臭杰,地道東北人粤咪。 一個月前我還...
    沈念sama閱讀 47,693評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像渴杆,于是被迫代替她去往敵國和親寥枝。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,577評論 2 353

推薦閱讀更多精彩內(nèi)容