xml文件解析

parse(文件名)打开文件并解析,相比于xml少了打开文件那一步

from xml.etree import ElementTree as ET

# 直接解析xml文件
tree = ET.parse("xo.xml")

# 获取xml文件的根节点
root = tree.getroot()      通过getroot获取根节点
对于任何标签都可以有三个特征:标签名、标签属性、标签的文本内容(不一定都会把三个写全)
print(root.tag) # 标签名
print(root.attrib) # 标签属性
print(root.text) # 标签的文本内容

import xml.etree.ElementTree as ET  # 后面调用都用ET

tree = ET.parse("a.xml") # 直接解析xml文件
# print(tree) # <xml.etree.ElementTree.ElementTree object at 0x000001BA45A83828>
root = tree.getroot() # 获得xml文件的根节点
print(root) # <Element 'data' at 0x000001BA45967638>
print(list(root))
[<Element 'country' at 0x0000021A9FC2CDB8>, <Element 'country' at 0x0000021A9FEDB958>, <Element 'country' at 0x0000021A9FEDBAE8>]

对于任何标签都可以有三个特征:标签名、标签属性、标签的文本内容(不一定都会把三个写全)
print(root.tag) 标签名
print(root.attrib) 标签属性
print(root.text) 标签的文本内容

print(list(root.iter('year')))#全文搜索,找到所有
[<Element 'year' at 0x0000022042A441D8>, <Element 'year' at 0x0000022042A4BA48>, <Element 'year' at 0x0000022042A4BBD8>]

for year in root.iter('year'):
print(year.tag)
print(year.attrib) year # 没有标签的属性
print(year.text)
print('='*100)


print(root.find('country').attrib) #在root的子节点找,只找一个 # {'name': 'Liechtenstein'}
print(root.findall('country').attrib) #在root的子节点找,只找一个 # 错误
print([country.attrib for country in root.findall('country')]) #在root的子节点找,找所有
[{'name': 'Liechtenstein'}, {'name': 'Singapore'}, {'name': 'Panama'}]


1、查
遍历整个文档
for country in root: # 打印整个xml文档
print('============>国家 %s' %country.attrib)
for item in country:
print(item.tag)
print(item.attrib)
print(item.text)

2、改
for year in root.iter('year'):
print(year.tag)
year.attrib={'updated':'yes'} # 添加year标签属性
year.text=str(int(year.text)+1) # 年份加1 先转换成int进行

tree.write('a.xml')

3、增
for country in root:
rank=country.find('rank')
if int(rank.text) > 50:
# print('符号条的国家',country.attrib)
tag=ET.Element('egon')
tag.attrib={'updated':'yes'}
tag.text='NB'
country.append(tag)
#
tree.write('a.xml')
4、删

for country in root:
tag=country.find('egon')
# print(tag,bool(tag))
if tag is not None:
print('====>')
country.remove(tag)
tree.write('a.xml')

猜你喜欢

转载自www.cnblogs.com/Roc-Atlantis/p/9225281.html