ElementTree优点:
- 轻量级的 Python 式的 API ,它由一个 C 实现来提供,速度快。http://effbot.org/zone/celementtree.htm
- DOM 将整个 XML 加载进内存并且允许随机访问任何深度地元素。ET 没有必要加载整个文档到内存.
- ET 的性能的平均值和 SAX 差不多,但是 API 的效率更高一点,更方便使用。
Python 标准库中有两种实现ElementTree:
- 纯 Python 实现例如 xml.etree.ElementTree
- 速度快一点的C实现的 xml.etree.cElementTree
例子:pom.xml
<span style="font-weight: normal;"><?xml version="1.0" encoding="utf-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.china</groupId>
<artifactId>shanghai</artifactId>
<version>1.1.1.20141031</version>
<properties>
<package.id>1</package.id>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>groupid1</groupId></span>
<span style="white-space:pre"> </span><artifactId>artifactId1</artifactId>
<version>1.1.1.20150130-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>groupid2 </groupId>
<artifactId> artifactId2</artifactId>
<version>1.1.2.20150130-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>groupid3 </groupId>
<artifactId> artifactId3</artifactId>
<version>1.1.3.20150130-SNAPSHOT</version>
</dependency>
</project></span>
解析:
方法一:从硬盘文件中读取
<span style="font-weight: normal;">tree = ET.parse(POM_PATH)
root = tree.getroot()</span>
方法二:从string 中读取数据
<span style="font-weight: normal;">root = ET.fromstring(country_data_as_string)</span>
XML 是一种分级的数据形式,所以最自然的表示方法是将它表示为一棵树。ET 有两个对象来实现这个目的 - ElementTree 将整个 XML 解析为一棵树, Element 将单个结点解析为树.
每个Element包含:
- tag : 字符串类型,代表Element 的类型,比如<groupId>
- atrributes :以python 字典方式存储,比如根节点的 xmlns 属性。可用 Element.get() 获取,Element.set() 修改
- text : 节点内容
- an optionaltail string
- number of child elements :存储在Python 队列中
<span style="font-weight: normal;">for child in root:
print child.tag
print child.attrib</span>
结果:
{http://maven.apache.org/POM/4.0.0}modelVersion
{}
{http://maven.apache.org/POM/4.0.0}groupId
{}
{http://maven.apache.org/POM/4.0.0}artifactId
{}
{http://maven.apache.org/POM/4.0.0}version
{}
{http://maven.apache.org/POM/4.0.0}properties
{}
{http://maven.apache.org/POM/4.0.0}dependencies
{}
查找:
方法一:Element和 ElementTree 对象有一个 iter 方法可以对子结点进行深度优先遍历。 find()返回所查找tag的第一个值
for child in root.iter('%sdependency' %(POM_NS)):
print child.find('$sgroupId' %POM_NS).text
方法二:
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,
for child in root.findall('%sdependency' %(POM_NS)):
print child.find('%sgroupId' %POM_NS).text
# 命名空间
POM_NS = "{http://maven.apache.org/POM/4.0.0}"
关于命名空间,stackoverflower讨论
http://stackoverflow.com/questions/14853243/parsing-xml-with-namespace-in-python-elementtree
结果:
groupid1
groupid2
groupid3
修改:
ElementTree.write() 提供很便利的服务,下面代码修改<package.id>的值,加1,并增加属性'updateed'后写回文件
for id in root.iter('%spackage.id' % (POM_NS)):
print id.text
new_id = int(id.text) + 1
id.text = str(new_id)
id.set('updateed', 'yes')
tree.write(POM_PATH)</span>
print:
1
打开Pom.xml看到这行发生变化: <package.id updateed="yes">2</package.id>
删除:
增加:
SubElement() 方法
官网代码
代码:
<span style="font-weight: normal;"># -*- coding:utf-8 -*-
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
# 命名空间
POM_NS = "{http://maven.apache.org/POM/4.0.0}"
# POM文件路径
POM_PATH = "D:\\pom.xml"
tree = ET.parse(POM_PATH)
root = tree.getroot()
for child in root:
print child.tag
print child.attrib
for child in root.iter('%sdependency' % (POM_NS)):
print child.find('%sgroupId' % POM_NS).text
for child in root.findall('%sdependency' % (POM_NS)):
print child.find('%sgroupId' % POM_NS).text
for id in root.iter('%spackage.id' % (POM_NS)):
print id.text
new_id = int(id.text) + 1
id.text = str(new_id)
id.set('updateed', 'yes')
tree.write(POM_PATH)
</span>
参考:
python 脚本读取maven pom http://sujitpal.blogspot.com/2009/07/python-script-to-read-maven-xml.html
用 ElementTree 在 Python 中解析 XML http://pycoders-weekly-chinese.readthedocs.org/en/latest/issue6/processing-xml-in-python-with-element-tree.html
<span style="font-weight: normal;"><?xml version="1.0" encoding="utf-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.china</groupId>
<artifactId>shanghai</artifactId>
<version>1.1.1.20141031</version>
<properties>
<package.id>1</package.id>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>groupid1</groupId></span>
<span style="white-space:pre"> </span><artifactId>artifactId1</artifactId>
<version>1.1.1.20150130-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>groupid2 </groupId>
<artifactId> artifactId2</artifactId>
<version>1.1.2.20150130-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>groupid3 </groupId>
<artifactId> artifactId3</artifactId>
<version>1.1.3.20150130-SNAPSHOT</version>
</dependency>
</project></span>
解析:
<span style="font-weight: normal;">tree = ET.parse(POM_PATH)
root = tree.getroot()</span>
方法二:从string 中读取数据
<span style="font-weight: normal;">root = ET.fromstring(country_data_as_string)</span>
- tag : 字符串类型,代表Element 的类型,比如<groupId>
- atrributes :以python 字典方式存储,比如根节点的 xmlns 属性。可用 Element.get() 获取,Element.set() 修改
- text : 节点内容
- an optionaltail string
- number of child elements :存储在Python 队列中
<span style="font-weight: normal;">for child in root:
print child.tag
print child.attrib</span>
{}
{http://maven.apache.org/POM/4.0.0}groupId
{}
{http://maven.apache.org/POM/4.0.0}artifactId
{}
{http://maven.apache.org/POM/4.0.0}version
{}
{http://maven.apache.org/POM/4.0.0}properties
{}
{http://maven.apache.org/POM/4.0.0}dependencies
{}
方法一:Element和 ElementTree 对象有一个 iter 方法可以对子结点进行深度优先遍历。 find()返回所查找tag的第一个值
for child in root.iter('%sdependency' %(POM_NS)):
print child.find('$sgroupId' %POM_NS).text方法二:
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,
for child in root.findall('%sdependency' %(POM_NS)):
print child.find('%sgroupId' %POM_NS).text
# 命名空间
POM_NS = "{http://maven.apache.org/POM/4.0.0}"关于命名空间,stackoverflower讨论
http://stackoverflow.com/questions/14853243/parsing-xml-with-namespace-in-python-elementtree
groupid2
groupid3
ElementTree.write() 提供很便利的服务,下面代码修改<package.id>的值,加1,并增加属性'updateed'后写回文件
for id in root.iter('%spackage.id' % (POM_NS)):
print id.text
new_id = int(id.text) + 1
id.text = str(new_id)
id.set('updateed', 'yes')
tree.write(POM_PATH)</span>
<span style="font-weight: normal;"># -*- coding:utf-8 -*-
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
# 命名空间
POM_NS = "{http://maven.apache.org/POM/4.0.0}"
# POM文件路径
POM_PATH = "D:\\pom.xml"
tree = ET.parse(POM_PATH)
root = tree.getroot()
for child in root:
print child.tag
print child.attrib
for child in root.iter('%sdependency' % (POM_NS)):
print child.find('%sgroupId' % POM_NS).text
for child in root.findall('%sdependency' % (POM_NS)):
print child.find('%sgroupId' % POM_NS).text
for id in root.iter('%spackage.id' % (POM_NS)):
print id.text
new_id = int(id.text) + 1
id.text = str(new_id)
id.set('updateed', 'yes')
tree.write(POM_PATH)
</span>
本文介绍了使用Python的ElementTree库解析Maven的POM.xml文件的方法,包括从文件和字符串中读取XML,遍历、查找、修改、删除和增加XML元素,以及处理命名空间。
797

被折叠的 条评论
为什么被折叠?



