[python] xml.etree.ElementTree使用方法小结

特别注明:本文所使用的例子均来自于Python软件内置文档中“20.5. xml.etree.ElementTree — The ElementTree XML API”一节。

思考1:ElementTree class和Element class有何区别?

20.5.1.1节的首段就对这两个类做了说明,其实我先开始并没有特别注意到这两个类,但是在使用中发现竟然会有两个类,脑海中突然冒出一个问题——ElementTree class和Element class有何区别?

"ET has two classes for this purpose - ElementTree represents the whole XML document as a tree, and Element represents a single node in this tree. Interactions with the whole document (reading and writing to/from files) are usually done on the ElementTree level. Interactions with a single XML element and its sub-elements are done on the Element level."

挺佩服写文章的作者,将这个问题的答案写在了第一段,我猜测他在使用xml.etree.ElementTree的时候也曾经遇到过这个问题,这是一个最基本的问题,当然也是我们首先要了解的一个知识点。

思考2:使用xml.etree.ElementTree.fromstring()方法的时候遇到一个看似简单却很容易出错的问题

字符串中保存着一组xml代码,可以直接使用fromstring(text)方法。特别要注意的是,三引号(''')后面要紧跟跟xml代码,不能有回车

错误用法(三引号后面有回车)

# 这是错误用法!!!
country_data_as_string = '''
<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
'''
import xml.etree.ElementTree as ET
root = ET.fromstring(country_data_as_string)

此时会有如下报错提示,说明得很清楚,“XML or text declaration not at start of entity”:

Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    root = ET.fromstring(country_data_as_string)
  File "C:\Users\cherish\AppData\Local\Programs\Python\Python36-32\lib\xml\etree\ElementTree.py", line 1314, in XML
    parser.feed(text)
  File "<string>", line None
xml.etree.ElementTree.ParseError: XML or text declaration not at start of entity: line 2, column 0

正确用法(三引号后紧跟xml代码)

# 这是正确用法!!!
country_data_as_string = '''<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
'''
import xml.etree.ElementTree as ET
root = ET.fromstring(country_data_as_string)

思考3:Element Objects中iter(tag=None)方法会遍历当前节点下的所有子节点、孙节点等等

在Element Objects所有方法中,只有iter()是从当前节点开始遍历其下的所有子节点、孙节点、重孙节点等等一直进行下去。诸如find()、findall()、甚至是iterfind()都只能遍历子节点(subelement)。正如文档中对iter()方法的描述中最重要的一句——"The iterator iterates over this element and all elements below it, in document (depth first) order"。

另外,"20.5.1.4. Finding interesting elements"一节也说明了iter()与findall()的区别。

"Element has some useful methods that help iterate recursively over all the sub-tree below it (its children, their children, and so on). For example, Element.iter()."

"Element.findall() finds only elements with a tag which are direct children of the current element. Element.find() finds the first child with a particular tag."

一个简单的例子,从中可以看到iter()方法遍历了所有的节点。其中,country_data_as_string的内容同上。

>>> root=ET.fromstring(country_data_as_string)
>>> for child in root.iter():
	print(child.tag)

	
data
country
rank
year
gdppc
neighbor
neighbor
country
rank
year
gdppc
neighbor
country
rank
year
gdppc
neighbor
neighbor

思考4:拿到一个xml文档后如何快速处理数据

主要是两步:

1. 从xml文档中读取数据——使用parse()方法,此时返回ElementTree对象

2. 获取根节点——使用getroot()方法,此时返回Element对象

import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')  # step1
root = tree.getroot()                # step2

假设country_data.xml文档中的内容如下,执行完第二步后root就指向data节点,然后就可以根据自己的需求进行数据处理了。

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

 

### 回答1: Python中的xml.etree.ElementTree是一个用于解析和操作XML文档的模块。它提供了一种简单的方式来读取和写入XML文件,并且可以轻松地遍历XML文档的元素和属性。使用xml.etree.ElementTree模块,可以将XML文档转换为Python对象,然后对其进行操作和处理。 ### 回答2: Python xml.etree.elementtree 是一个 Python 模块,用于解析 XML 文档并创建 XML 元素树。这个模块提供了一种简单且高效的方式来处理 XML 数据,可以帮助开发者轻松地构建 Python 对象/字典和 XML 文档之间的映射。 使用 xml.etree.ElementTree,可以将 XML 文档转换为元素对象树,然后使用元素对象进行文档处理。使用这个模块可以很容易地将 XML 数据解析和转换为 Python 中的数据类型,例如列表、字典和字符串等。同时,ElementTree 还支持 XPath 表达式(XPath 是一种用于选取 XML 文档中数据的语言)。 ElementTree 将一个 XML 文档解析成一个通用的元素树结构,将每个元素作为 Python 对象中的一个元素。在几乎所有的XML处理扩展中,ElementTree都是标准的API。其重要的特点包括: 1. 简单易用的API,支持解析和生成XML; 2. 支持遍历解析XML文档; 3. 支持XPath定位; 4. 遵守XML标准,并且能够正确处理XML文档中的编码格式、属性和命名空间等细节; 5. 兼容Python3与Python2. 在Python应用领域中,XML是一种常见格式,如SOAP和RESTful Web Services、HTML、配置文件等等。使用 ElementTree,可以方便地处理这些数据供应用完成数据处理,构建XML数据请求和响应等。总之,Python xml.etree.elementtree 是一个基于 XML 的开发框架,可用于快速,可靠地构建和解析 XML 文档。 ### 回答3: Python 中的 xml.etree.elementtree 是一个用于操作 XML 数据的库。ElementTree 是 Element 的树形结构,允许对其进行操作并将其转换为 XML 文件或字符串。它被广泛应用于 Web 开发和数据处理,例如在面向 XML 数据的 Web 应用程序和配置文件中。 ElementTree 提供了一个对 XML 元素进行递归访问的 API。通过向 XML 解析器提供 XML 文件路径或 URL,ElementTree 可以读取 XML 文件并将其转换为一个 element 对象。通过 element 对象,我们可以获得元素的文本内容、属性、子元素、标签等信息。 ElementTree 还提供了一些实用函数,帮助我们轻松地操作 XML 数据。例如,我们可以使用 find() 和 findall() 函数搜索 Element 中的子元素,并使用 set() 函数设置元素的属性、text 属性来获取或设置元素的文本内容。 在使用 xml.etree.elementtree 进行 XML 数据处理时,我们还可以使用 lxml、BeautifulSoup 和 html5lib 等库,以便更方便地解析、操作和处理 XML 数据。 总之,Python 中的 xml.etree.elementtree 提供了强大的 XML 数据处理功能,使得我们可以轻松地访问、解析和操作 XML 数据。无论是 Web 应用程序还是常规数据处理,ElementTree 都是一个值得信赖和广泛运用的库。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值