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 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 elementroot = 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文件具有以下内容:

<users><user /></users>

There are two things to notice here:

这里有两件事要注意:

  • While writing the file, we used wb mode instead of w as we need to write the file 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 elementroot = 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:

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

<users><user><id>123</id><name>Shubham</name></user>
</users>

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文件。 我们只是向其中添加了更多数据:

<users><user><id>123</id><name>Shubham</name><salary>0</salary></user><user><id>234</id><name>Pankaj</name><salary>0</salary></user><user><id>345</id><name>JournalDev</name><salary>0</salary></user>
</users>

Let’s try and update salaries of each user:

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

import xml.etree.ElementTree as xmldef updateXML(filename):# Start with the root elementtree = 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 xmldef parseXML(file_name):# Parse XML with ElementTreetree = 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.

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

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: API Doc

参考: API文档

翻译自: https://www.journaldev.com/18094/python-xml-parser-elementtree

Python XML解析器– ElementTree相关推荐

  1. python解析xml文件elementtree_Python XML解析之ElementTree

    参考网址: 菜鸟教程提供了基本的XML编程接口DOM.SAX,以及轻量级ElementTree的简易概念说明和一些示例.DOM是一种跨语言的XML解析机制,通过将整个XML在内存中解析为一个树来操作, ...

  2. Python XML解析

    什么是XML? XML 指可扩展标记语言(eXtensible Markup Language). 你可以通过本站学习XML教程 XML 被设计用来传输和存储数据. XML是一套定义语义标记的规则,这 ...

  3. Python XML解析方法

    XML介绍 XML(eXtensible Markup Language,可扩展标记语言):一种用于标记电子文件使其具有结构性的标记语言,被用来传输和存储数据 XML文档结构:一种树结构,从根部开始, ...

  4. XML解析器列表(超全!)

    XML解析器列表(超全!) AdvXMLParser  Sebastien Andrivet  C++   Arabica  Jez Higgins  C++   CL-XML  James Ande ...

  5. python菜鸟驿站-Python XML 解析

    1.对大型文件进行处理: 2.只需要文件的部分内容,或者只需从文件中得到特定信息. 3.想建立自己的对象模型的时候. 在python中使用sax方式处理xml要先引入xml.sax中的parse函数, ...

  6. Java XML解析器

    使用Apache Xerces解析XML文档 一.技术概述 在用Java解析XML时候,一般都使用现成XML解析器来完成,自己编码解析是一件很棘手的问题,对程序员要求很高,一般也没有专业厂商或者开源组 ...

  7. TinyXML:一个优秀的C++ XML解析器

    读取和设置xml配置文件是最常用的操作,试用了几个C++的XML解析器,个人感觉TinyXML是使用起来最舒服的,因为它的API接口和Java的十分类似,面向对象性很好. TinyXML是一个开源的解 ...

  8. 先弄个XML解析器代码抄一抄 慢慢研究 O(∩_∩)O哈哈~

     出处:http://bbs.csdn.net/topics/390229172 已经自我放逐好几年了.打算去上班得了.在最后的自由日子里,做点有意义的事吧... 先来下载地址    http:/ ...

  9. Phinecos(洞庭散人) 专注于开源技术的研究与应用 TinyXML:一个优秀的C++ XML解析器

    读取和设置xml配置文件是最常用的操作,试用了几个C++的XML解析器,个人感觉TinyXML是使用起来最舒服的,因为它的API接口和Java的十分类似,面向对象性很好. TinyXML是一个开源的解 ...

最新文章

  1. Javascript history pushState onpopstate方法做AJAX SEO
  2. 【转】常见浏览器兼容性问题与解决方案css篇
  3. 《CUDA高性能并行计算》----2.2 需要知道的CUDA API和C语言拓展
  4. 光伏产业的发展推动太阳能组件技术进步
  5. 闭包 —JavaScript面向对象高级
  6. 时间都去哪儿了之Python程序测试与优化
  7. DocumentFragment文档片段示例
  8. 企业IT构建核心基础架构解决方案
  9. Mac adb 安装
  10. 一种视频录制时,类似监控视频中加入动态时间标记的装置
  11. Android应用程序层的作用,Android应用程序框架-004.bean层
  12. hover和active的区别
  13. 频点换算计算器android,LTE频率频点计算器
  14. js怎么实现hmacsha256_各种语言HMAC SHA256实现
  15. 如何将Chrome设为iPhone和iPad上的默认Web浏览器
  16. 城市交通类毕业论文文献包含哪些?
  17. Java实验4-1【数组下标越界异常处理】
  18. windows桌面图标或状态栏图标显示空白或无法正常显示
  19. 空间申请(malloc)与释放(free)——C语言
  20. gazebo mesh尝试dae

热门文章

  1. biztalk 2006 产品的版本以及适配器相关信息
  2. 已解决——pycharm在同目录下import,pycharm会提示错误,但是可以运行
  3. [转载] python 使用pandas进行读写excel文件操作
  4. [转载] Visual Studio 2017 VC项目设置 printf 输出到 Console 窗口调试
  5. Beta阶段第1周/共2周 Scrum立会报告+燃尽图 06
  6. 学习simple.data之基础篇
  7. javascript 使用canvas绘画
  8. 自动驾驶算法-滤波器系列(八)——IMM交互多模型介绍
  9. 【Proteus仿真】220V转5V向单片机供电
  10. python显示当前日期_python显示当前时间