前言:
在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)