Home  >  Article  >  Backend Development  >  Example analysis of methods for accessing XML using Python

Example analysis of methods for accessing XML using Python

高洛峰
高洛峰Original
2017-03-22 09:22:111170browse

这篇文章主要介绍了Python存取XML的常见方法,结合具体实例形式较为详细的分析了Python存取xml的常用方法、优缺点比较与相关注意事项,需要的朋友可以参考下

本文实例讲述了Python存取XML的常见方法。分享给大家供大家参考,具体如下:

目前而言,Python 3.2存取XML有以下四种方法:

1.Expat
2.DOM
3.SAX
4.ElementTree

以以下xml作为讨论依据

<?xml version="1.0" encoding="utf-8"?>
<Schools>
  <School Name="XiDian">
    <Class Id="030612">
      <Student Name="salomon">
        <Scores>
          <Math>98</Math>
          <English>85</English>
          <physics>89</physics>
        </Scores>
      </Student>
      <Student Name="Jupiter">
        <Scores>
          <Math>74</Math>
          <English>83</English>
          <physics>69</physics>
        </Scores>
      </Student>
    </Class>
    <Class Id="030611">
      <Student Name="Venus">
        <Scores>
          <Math>98</Math>
          <English>85</English>
          <physics>89</physics>
        </Scores>
      </Student>
      <Student Name="Mars">
        <Scores>
          <Math>74</Math>
          <English>83</English>
          <physics>69</physics>
        </Scores>
      </Student>
    </Class>
  </School>
</Schools>

Expat

Expat是一个面向流的解析器。您注册的解析器回调(或handler)功能,然后开始搜索它的文档。当解析器识别该文件的指定的位置,它会调用该部分相应的处理程序(如果您已经注册的一个)。该文件被输送到解析器,会被分割成多个片断,并分段装到内存中。因此expat可以解析那些巨大的文件。

SAX

SAX是个循序存取XML的解析器API,一个实现SAX的解析器(也就是“SAX Parser”)以一个串流解析器的型式作用,拥有事件驱动API。由使用者定义回调函数,解析时,若发生事件的话会被调用。事件在任一XML特性遇到时引发,以及遇到他们结尾时再次引发。XML属性也作为传给元素事件资料的一部分。SAX 处理时单方向性的;解析过的资料无法在不重新开始的情况下再次读取。

DOM

DOM解析器在任何处理开始之前,必须把整棵树放在内存,所以DOM解析器的内存使用量完全根据输入资料的大小(相对来说,SAX解析器的内存内容,是只基于XML档案的最大深度(XML树的最大深度)和单一XML项目上XML属性储存的最大资料)。

DOM在python3.2中有两种实现方式:

1.xml.minidom是一个基本的实现。
2.xml.pulldom只在需要时构建被访问的子树。

&#39;&#39;&#39;
Created on 2012-5-25
@author: salomon
&#39;&#39;&#39;
import xml.dom.minidom as minidom
dom = minidom.parse("E:\\test.xml")
root = dom.getElementsByTagName("Schools") #The function getElementsByTagName returns NodeList.
print(root.length)
for node in root: 
  print("Root element is %s。" %node.tagName)# 格式化输出,与C系列语言有很大区别。
  schools = node.getElementsByTagName("School")
  for school in schools:
    print(school.nodeName)
    print(school.tagName)
    print(school.getAttribute("Name"))
    print(school.attributes["Name"].value)
    classes = school.getElementsByTagName("Class")
    print("There are %d classes in school %s" %(classes.length, school.getAttribute("Name")))
    for mclass in classes:
      print(mclass.getAttribute("Id"))
      for student in mclass.getElementsByTagName("Student"):
        print(student.attributes["Name"].value)
        print(student.getElementsByTagName("English")[0].nodeValue) #这个为什么啊?
        print(student.getElementsByTagName("English")[0].childNodes[0].nodeValue)
        student.getElementsByTagName("English")[0].childNodes[0].nodeValue = 75
f = open(&#39;new.xml&#39;, &#39;w&#39;, encoding = &#39;utf-8&#39;)
dom.writexml(f,encoding = &#39;utf-8&#39;)
f.close()

ElementTree

目前搜到的ElementTree的信息较少,目前不知道其工作机制。有资料显示ElementTree近乎一种轻量级的DOM,但是ElementTree 所有的 Element 节点的工作方式是一致的。它很类似于C#中的XpathNavigator。

&#39;&#39;&#39;
Created on 2012-5-25
@author: salomon
&#39;&#39;&#39;
from xml.etree.ElementTree import ElementTree
tree = ElementTree()
tree.parse("E:\\test.xml")
root = tree.getroot()
print(root.tag)
print(root[0].tag)
print(root[0].attrib)
schools = root.getchildren() 
for school in schools:
  print(school.get("Name"))
  classes = school.findall("Class")
  for mclass in classes:
    print(mclass.items())
    print(mclass.keys())
    print(mclass.attrib["Id"])
    math = mclass.find("Student").find("Scores").find("Math")
    print(math.text)
    math.set("teacher", "bada")
tree.write("new.xml")

Compare:

就以上几点来说Expat和SAX解析XML方式相同,就是不知道性能相比怎样。DOM相对于以上两种解析器,消耗内存,而且由于存取耗时,所以处理文件相对来说慢。如果文件太大无法载入内存,DOM这种解析器就不能用了,但是对于,某些种类的XML验证需要存取整份文件,或者某些XML处理仅要求存取整份文件的需求时,DOM是唯一选择。

Note:

需要指出的是存取XML的这几项技术并不是Python独创的,Python也是通过借鉴其他语言或者直接从其他语言引入进来的。例如Expat就是一个用C语言开发的、用来解析XML文档的开发库。而SAX最初是由DavidMegginson采用java语言开发的,DOM可以以一种独立于平台和语言的方式访问和修改一个文档的内容和结构。可以应用于任何编程语言

做为对比我也想列举一下C#存取XML文档的方式:

1. 基于DOM的XmlDocument
2. 基于流文件的XmlReader 和 XmlWriter(它和SAX流文件实现不同,SAX是事件驱动模型)。
3. Linq to Xml

流文件两种模型:XmlReader/XMLWriter VS SAX

流模型每次迭代XML文档中的一个节点,适合于处理较大的文档,所耗内存空间小。流模型中有两种变体——“推”模型和“拉”模型。

推模型也就是常说的SAX,SAX是一种靠事件驱动的模型,也就是说:它每发现一个节点就用推模型引发一个事件,而我们必须编写这些事件的处理程序,这样的做法非常的不灵活,也很麻烦。

.NET uses an implementation plan based on the "pull" model. When traversing the document, the "pull" model will pull the document part of interest from the reader without triggering an event, allowing us to program Access documents in this way, which greatly improves flexibility. In terms of performance, the "pull" model can selectively process nodes, and SAX will notify the client every time it finds a node. Therefore, using the "pull" model can improve the overall performance of the Application. efficiency.

The above is the detailed content of Example analysis of methods for accessing XML using Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn