一 xml数据结构
<data info="student">
<name>小明</name>
<age>18</age>
<gender>男</gender>
</data>
上述就是一个简单的xml数据,这里有几个概念,包括:
根元素 <data>
子元素 <name><age>…
标签 带<>都是标签<data>是开始标签,</data>是结束标签
属性 开始标签中有其它信息的是属性如data标签中的info
文本 被开始标签和结束标签包含的是文本,如小明
二 入门实验代码
#try: #采用底层为c的库,速度快,内存占用小
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")
三 实验输出结果
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
四 参考网址:
1. https://blog.csdn.net/wklken/article/details/7603071?utm_source=blogxgwz7
2. https://blog.csdn.net/weixin_30549657/article/details/98340427
网友评论