博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python XML解析器– ElementTree
阅读量:2533 次
发布时间:2019-05-11

本文共 5584 字,大约阅读时间需要 18 分钟。

Python XML parser provides us an easy way to read the XML file and extract useful data. Today we will look into python ElementTree XML API and learn how to use it to parse XML file as well as modify and create XML documents.

Python XML解析器为我们提供了一种读取XML文件并提取有用数据的简便方法。 今天,我们将研究python ElementTree XML API,并学习如何使用它来解析XML文件以及修改和创建XML文档。

Python XML解析器– Py​​thon ElementTree (Python XML Parser – Python ElementTree)

python xml parser, python elementtree
Python ElementTree is one of the most efficient APIs to extract, parse and transform XML data using Python programming language. In this post, we will have good look at how to create, read, parse and update XML data in files and programmatically.

Python ElementTree是使用Python编程语言提取,解析和转换XML数据的最有效API之一。 在本文中,我们将很好地了解如何以编程方式创建,读取,解析和更新文件中的XML数据。

Let’s get started with Python XML parser examples using ElementTree.

让我们开始使用ElementTree的Python XML解析器示例。

Python ElementTree示例 (Python ElementTree examples)

We will start with a very simple example to create an XML file programmatically and then, we will move to more complex files.

我们将从一个非常简单的示例开始,以编程方式创建XML文件,然后,我们将转向更复杂的文件。

创建XML文件 (Creating XML file)

In this example, we will create a new XML file with an element and a sub-element. Let’s get started straight away:

在此示例中,我们将创建一个带有一个元素和一个子元素的新XML文件。 让我们立即开始:

import xml.etree.ElementTree as xmldef createXML(filename):    # Start with the root element    root = xml.Element("users")    children1 = xml.Element("user")    root.append(children1)    tree = xml.ElementTree(root)    with open(filename, "wb") as fh:        tree.write(fh)if __name__ == "__main__":    createXML("test.xml")

Once we run this script, a new file will be created in the same directory with file named as test.xml with following contents:

一旦运行此脚本,将在同一目录中创建一个新文件,名为test.xml文件具有以下内容:

There are two things to notice here:

这里有两件事要注意:

  • While writing the file, we used wb mode instead of w as we need to in binary mode.

    写入文件时,我们使用wb模式而不是w因为我们需要以二进制模式 。
  • The child user tag is a self-closing tag as we haven’t put any sub-elements in it.

    子用户标签是一个自动关闭的标签,因为我们没有在其中添加任何子元素。

向XML元素添加值 (Adding values to XML elements)

Let’s improve the program by adding values to the XML elements:

让我们通过向XML元素添加值来改进程序:

import xml.etree.ElementTree as xmldef createXML(filename):    # Start with the root element    root = xml.Element("users")    children1 = xml.Element("user")    root.append(children1)    userId1 = xml.SubElement(children1, "id")    userId1.text = "123"    userName1 = xml.SubElement(children1, "name")    userName1.text = "Shubham"    tree = xml.ElementTree(root)    with open(filename, "wb") as fh:        tree.write(fh)if __name__ == "__main__":    createXML("test.xml")

Once we run this script, we will see that new elements are added added with values. Here are the content of the file:

运行此脚本后,我们将看到添加了新元素并添加了值。 这是文件的内容:

123
Shubham

This is perfectly valid XML and all tags are closed. Please note that I formatted the XML myself as the API writes the complete XML in a single fine which is kind a bit, incompleteness!

这是完全有效的XML,并且所有标签均已关闭。 请注意,我自己格式化了XML,因为API一口气写出了完整的XML,这有点不完整!

Now, let’s start with editing files.

现在,让我们开始编辑文件。

编辑XML数据 (Editing XML data)

We will use the same XML file we showed above. We just added some more data into it as:

我们将使用上面显示的相同XML文件。 我们只是向其中添加了更多数据:

123
Shubham
0
234
Pankaj
0
345
JournalDev
0

Let’s try and update salaries of each user:

让我们尝试更新每个用户的薪水:

import xml.etree.ElementTree as xmldef updateXML(filename):    # Start with the root element    tree = xml.ElementTree(file=filename)    root = tree.getroot()    for salary in root.iter("salary"):        salary.text = '1000'     tree = xml.ElementTree(root)    with open("updated_test.xml", "wb") as fh:        tree.write(fh)if __name__ == "__main__":    updateXML("test.xml")

It is worth noticing that if you try to update an elements value to an integer, it won’t work. You will have to assign a String, like:

值得注意的是,如果您尝试将元素值更新为整数,将无法使用。 您将必须分配一个字符串,例如:

salary.text = '1000'

instead of doing:

而不是做:

salary.text = 1000

Python XML解析器示例 (Python XML Parser Example)

This time, let’s try to parse the XML data present in the file and print the data:

这次,让我们尝试解析文件中存在的XML数据并打印数据:

import xml.etree.cElementTree as xml def parseXML(file_name):    # Parse XML with ElementTree    tree = xml.ElementTree(file=file_name)    print(tree.getroot())    root = tree.getroot()    print("tag=%s, attrib=%s" % (root.tag, root.attrib))     # get the information via the children!    print("-" * 40)    print("Iterating using getchildren()")    print("-" * 40)    users = root.getchildren()    for user in users:        user_children = user.getchildren()        for user_child in user_children:            print("%s=%s" % (user_child.tag, user_child.text)) if __name__ == "__main__":    parseXML("test.xml")

When we run above script, below image shows the output produced.

python elementtree example, python xml parser example

当我们在脚本上方运行时,下图显示了生成的输出。

In this post, we studied how to extract, parse, and transform XML files. ElementTree is one of the most efficient APIs to do these tasks. I would suggest you try some more examples of XML parsing and modifying different values in XML files.

在本文中,我们研究了如何提取,解析和转换XML文件。 ElementTree是执行这些任务的最高效的API之一。 我建议您尝试更多XML解析和修改XML文件中不同值的示例。

Reference:

参考:

翻译自:

转载地址:http://bymzd.baihongyu.com/

你可能感兴趣的文章
阶段3 3.SpringMVC·_07.SSM整合案例_08.ssm整合之Spring整合MyBatis框架
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第2节 SpringBoot接口Http协议开发实战_9、SpringBoot基础HTTP其他提交方法请求实战...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第2节 SpringBoot接口Http协议开发实战_12、SpringBoot2.x文件上传实战...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第4节 Springboot2.0单元测试进阶实战和自定义异常处理_19、SpringBoot个性化启动banner设置debug日志...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第4节 Springboot2.0单元测试进阶实战和自定义异常处理_20、SpringBoot2.x配置全局异常实战...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第5节 SpringBoot部署war项目到tomcat9和启动原理讲解_23、SpringBoot2.x启动原理概述...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第4节 Springboot2.0单元测试进阶实战和自定义异常处理_21、SpringBoot2.x配置全局异常返回自定义页面...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第8节 数据库操作之整合Mybaties和事务讲解_32..SpringBoot2.x持久化数据方式介绍...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第8节 数据库操作之整合Mybaties和事务讲解_34、SpringBoot整合Mybatis实操和打印SQL语句...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第8节 数据库操作之整合Mybaties和事务讲解_35、事务介绍和常见的隔离级别,传播行为...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第9节 SpringBoot2.x整合Redis实战_40、Redis工具类封装讲解和实战...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第9节 SpringBoot2.x整合Redis实战_37、分布式缓存Redis介绍...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第10节 SpringBoot整合定时任务和异步任务处理_42、SpringBoot常用定时任务配置实战...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第9节 SpringBoot2.x整合Redis实战_39、SpringBoot2.x整合redis实战讲解...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第14节 高级篇幅之SpringBoot多环境配置_59、SpringBoot多环境配置介绍和项目实战...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第10节 SpringBoot整合定时任务和异步任务处理_41、SpringBoot定时任务schedule讲解...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第10节 SpringBoot整合定时任务和异步任务处理_43、SpringBoot2.x异步任务实战(核心知识)...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_1_01课程简介
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第11节 Logback日志框架介绍和SpringBoot整合实战_45、SpringBoot2.x日志讲解和Logback配置实战...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_1_02技术选型
查看>>