一 xml數(shù)據(jù)結(jié)構(gòu)
<data info="student">
<name>小明</name>
<age>18</age>
<gender>男</gender>
</data>
上述就是一個(gè)簡(jiǎn)單的xml數(shù)據(jù),這里有幾個(gè)概念,包括:
根元素 <data>
子元素 <name><age>…
標(biāo)簽 帶<>都是標(biāo)簽<data>是開始標(biāo)簽,</data>是結(jié)束標(biāo)簽
屬性 開始標(biāo)簽中有其它信息的是屬性如data標(biāo)簽中的info
文本 被開始標(biāo)簽和結(jié)束標(biāo)簽包含的是文本,如小明
二 入門實(shí)驗(yàn)代碼
#try: #采用底層為c的庫(kù),速度快,內(nèi)存占用小
import xml.etree.cElementTree as ET
#except ImportError:
#import xml.etree.ElementTree as ET
#doc = ET.parse('test.xml')
# 打開xml文檔
doc = ET.ElementTree(file='test.xml')
root = doc.getroot()
print(root.tag)
print( root.attrib)
print("study1")
for child_of_root in root:
print(child_of_root.tag,child_of_root.attrib,child_of_root.text)
print("study2")
print(root[0].tag, root[0].text)
print("study3")
for elem in doc.iter():
print(elem.tag, elem.attrib)
print("study4")
for elem in doc.iter(tag="branch"):
print(elem.tag, elem.attrib)
print("study5")
# 查詢
for elem in doc.iterfind('branch/sub-branch'):
print(elem.tag, elem.attrib)
print("study6")
for elem in doc.iterfind('branch[@name="release01"]'):
print(elem.tag, elem.attrib)
print("study7")
# 若key存在則是修改,否則為添加屬性
root[0].set('name', 'Apple3')
print(root[0].attrib)
# 刪除屬性
del root[0].attrib['name']
print(root[0].attrib)
for subelem in root:
print(subelem.tag, subelem.attrib)
print("study8")
# 將修改寫入xml文檔
doc.write('test.xml')
print("write ok")
三 實(shí)驗(yàn)輸出結(jié)果
doc
{}
study1
branch {'foo': 'bar', 'hash': '1cdf045c', 'name2': 'Apple2'}
text,source
branch {'hash': 'f200013e', 'name': 'release01'}
branch {'name': 'invalid'}
study2
branch
text,source
study3
doc {}
branch {'foo': 'bar', 'hash': '1cdf045c', 'name2': 'Apple2'}
branch {'hash': 'f200013e', 'name': 'release01'}
sub-branch {'name': 'subrelease01'}
branch {'name': 'invalid'}
study4
branch {'foo': 'bar', 'hash': '1cdf045c', 'name2': 'Apple2'}
branch {'hash': 'f200013e', 'name': 'release01'}
branch {'name': 'invalid'}
study5
sub-branch {'name': 'subrelease01'}
study6
branch {'hash': 'f200013e', 'name': 'release01'}
study7
{'foo': 'bar', 'hash': '1cdf045c', 'name2': 'Apple2', 'name': 'Apple3'}
{'foo': 'bar', 'hash': '1cdf045c', 'name2': 'Apple2'}
branch {'foo': 'bar', 'hash': '1cdf045c', 'name2': 'Apple2'}
branch {'hash': 'f200013e', 'name': 'release01'}
branch {'name': 'invalid'}
study8
ok
四 參考網(wǎng)址:
1. https://blog.csdn.net/wklken/article/details/7603071?utm_source=blogxgwz7
2. https://blog.csdn.net/weixin_30549657/article/details/98340427