tag:即标签,用于标识该元素表示哪种数据
eg:<data>用<>括起来的为标签
提取:obj.tag
attrib:即属性,用字典形式保存,即{'channel'='CSDN'}
eg:<country name='Liechtenstein'>中name="Liechtenstein"为属性,用字典形式表示
提取:obj.attrib
text:文本字符串,并不是必须的
eg:<rank>1<rank>中的1为标签rank的text
提取:obj.text
格式:
a= open(xml_file_path)
tree=ET.parse(a)
root = tree.getroot() #获取根节点
import xml.etree.ElementTree as ET
data='''
<person>
<name>Chuck</name>
<phone type="intl">
+1 734 303 4456
</phone>
<email hide="yes"/>
</person>'''
#data = open("XXX.xml").read() 做演示省略了读取文件这一步
root=ET.fromstring(data) #固定格式:得到根节点root
Name=root.find('name') #tree.find(<XX>)
Attr=root.find('email')
print('Name:',Name.text) #<>.text
print('Attr:',Attr.get('hide'))
#得到根节点下面的数据:
root=ET.fromstring(data)
for i in root:
print(i.tag)
print(i.attrib)
结果:
name
{}
phone
{'type': 'intl'}
email
{'hide': 'yes'}
#得到具体的数据:
root=ET.fromstring(data)
for i in root.findall('email'): #若查找所有该标记节点数据用for i in root.iter('email'):
print(i.tag)
print(i.attrib)
结果:
email
{'hide': 'yes'}
部分借鉴:https://blog.csdn.net/m0_37857151/article/details/84037148