import xml.etree.ElementTree as ET
tree = ET.parse('xml_test')
root = tree.getroot() # 获取 根节点
print(root.tag)
# 遍历xml文档
for child in root:
print(child.tag, child.attrib) # 获取下一级的标签和属性
for i in child:
print(' ', i.tag, i.text) # 获取再下一级的标签和文本
# 只遍历year 节点
for node in root.iter('year'): # 在 根节点的子节点中过滤出标签‘year’
print(node.tag, node.text) # 打印节点标签和文本
# 修改
for node in root.iter('year'):
new_year = int(node.text) + 1 # 修改获取到的文本 (先转为int 型)
node.text = str(new_year) # 再转为string 型
node.set("updated", "yes") # 给指定标签 赋值
tree.write("update.xml") # 持久化
# 删除node
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country) # remove() 方法
tree.write('delete.xml')
操作文件:xml_test.xml
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
<!--xml数据-->
要点:
- parse('file') 解析文件
- getroot() 获取根节点
- 根节点可遍历:for child in root: child.tag,child.attrib 其中child.tag 获取子节点标签,child.attrib 获取子节点属性值
- 上面的child 也是可遍历对象: for i in child: i.tag , i.text 其中i.tag 获取标签,i.text 获取文本
- iter() 过滤字段
- findall() 匹配字段
# 序列化:内存中变成可存储,可传输的过程称之为序列化
# json 流行,更简单
# xml 过时的机制 在java