2022年 11月 5日

Python解析xml文件详解

1、如何解析简单的xml文档?

        实际案例:

                xml是一种十分常用的标记性语言,可提供统一的方法来描述应用程序的结构化数据:

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <data>
  3. <country name="Liechtenstein">
  4. <rank updated="yes">2</rank>
  5. <year>2008</year>
  6. <gdppc>141100</gdppc>
  7. <neighbor name="Austria" direction="E"/>
  8. <neighbor name="Switzerland" direction="W"/>
  9. </country>
  10. </data>

                python中如何解析xml文档?

        解决方案:

                使用标准库中的xml.etree.ElementTree,其中的parse函数可以解析XML文档。

2、代码演示

(1)使用parse解析XML文档

  1. from xml.etree.ElementTree import parse
  2. f = open('demo.xml')
  3. # 第1个参数为输入源,返回一个ElementTree对象
  4. et = parse(f)
  5. # 通过元素树(ElementTree)得到根结点
  6. root = et.getroot()
  7. print(root)
  8. # 查看标签
  9. print(root.tag)
  10. # 查看属性
  11. print(root.attrib)
  12. # 查看文本,去除空格
  13. print(root.text.strip())
  14. # 遍历元素树
  15. # 得到节点的子元素,python3中getchildren被废弃
  16. children = list(root)
  17. print(children)
  18. # 获取每个子节点元素的属性
  19. for child in root:
  20. print(child.get('name'))
  21. '''
  22. find、findall和iterfind只能找对于
  23. 当前的元素它的直接子元素,不能查找孙子元素。
  24. '''
  25. # 根据标签寻找子元素,find总是找到第1个碰到的元素
  26. print(root.find('country'))
  27. # findall是找到所有的的元素
  28. print(root.findall('country'))
  29. # 不需要列表,希望是一个可迭代对象,得到一个生成器对象
  30. print(root.iterfind('country'))
  31. for e in root.iterfind('country'):
  32. print(e.get('name'))
  33. # 无论在那个层级下都能找到rank标签
  34. # 在默认情况下不输入参数,会列出整个当前节点之下的所有元素
  35. print(list(root.iter()))
  36. # 递归的去寻找标签为rank的子节点
  37. print(list(root.iter('rank')))

(2)关于findall查找的高级用法

  1. from xml.etree.ElementTree import parse
  2. f = open('demo.xml')
  3. # 第1个参数为输入源,返回一个ElementTree对象
  4. et = parse(f)
  5. # 通过元素树(ElementTree)得到根结点
  6. root = et.getroot()
  7. # *能匹配所有的child,只想找root的所有孙子节点
  8. print(root.findall('country/*'))
  9. # 查找任意层次下的子元素,.点为当前节点,..为父节点
  10. print(root.findall('.//rank'))
  11. print(root.findall('.//rank/..'))
  12. # @描述包含某一属性,[@attrib]
  13. print(root.findall('country[@name]'))
  14. # 指定属性为特定值,[@attrib='value']
  15. print(root.findall('country[@name="Singapore"]'))
  16. # 指定一个元素必须包含一个指定的子元素,[tag]
  17. print(root.findall('country[rank]'))
  18. # 指定元素的文本必须等于特定的值,[tag='text']
  19. print(root.findall('country[rank="5"]'))
  20. # 找多个元素路径指定相对位置,[position]
  21. print(root.findall('country[1]'))
  22. print(root.findall('country[2]'))
  23. # last()为倒着找
  24. print(root.findall('country[last()]'))
  25. # 找倒数第二个
  26. print(root.findall('country[last()-1]'))