Accessing an element's parent with ElementTree(转)
Today I ran across a situation where I needed to programmatically remove specific elements from a KML file. I was already using Python's ElementTree library for my KML processing, so I attempted to use ElementTree's remove() method. The remove() method can only remove subelements, requiring access to the undesired element's parent.
No problem, right? Even though there isn't a parent attribute or getparent() method for elements, ElementTree 1.3 introduced an XPath expression to get an element's parent.
Python 2.7.2+ (default, Oct 4 2011, 20:06:09)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import xml.etree.ElementTree as et
>>> et.VERSION
'1.3.0'
>>> tree = et.parse('test.kml')
>>> xmlns = '{http://www.opengis.net/kml/2.2}'
>>> elem = tree.find('.//%scolorMode' % xmlns)
>>> elem
<Element '{http://www.opengis.net/kml/2.2}colorMode' at 0x7f4bfc04a650>
>>>
>>> elem.find('..')
>>>
Turns out, that's not how things work in the world of ElementTree. An element actually has no reference back to its parent, thus explaining the lack of a getparent() type method for the element...and why elem.find('..') returns None.
There are a couple different solutions at this point. You can create a generator that will iterate over your tree, returning (parent, child) tuples (detailed here) or use lxml, which is ElementTree compliant and supports a getparent() method for elements.
However, if you're like me, you'll feel an inability to move on until you figure out why the XPath isn't working like you think it should. You might be tempted to think that something is broken with ElementTree, but, as is almost always the case, the problem is a user error.
It actually took a fair amount of thinking and a suggestion from my good friend Ryan to figure this out. Basically, since the element doesn't contain a reference to its parent, we need to go up a level (to the tree) in order to get the parent node using the '..' XPath expression.
>>> tree.find('.//%scolorMode/..' % xmlns)
<Element '{http://www.opengis.net/kml/2.2}LineStyle' at 0x7f4bfc04a490>
Now you have the parent element, so removing the undesired child element (colorMode, in this case) is relatively simple.
>>> parents = tree.findall('.//%scolorMode/..' % xmlns)
>>>
>>> for parent in parents:
... parent.remove(parent.find('%scolorMode' % xmlns))
...
>>>
Accessing an element's parent with ElementTree(转)的更多相关文章
- Element DOM Tree jQuery plugin – Firebug like functionality | RockingCode
Element DOM Tree jQuery plugin – Firebug like functionality | RockingCode Element DOM Tree jQuery pl ...
- Python之xml文档及配置文件处理(ElementTree模块、ConfigParser模块)
本节内容 前言 XML处理模块 ConfigParser/configparser模块 总结 一.前言 我们在<中我们描述了Python数据持久化的大体概念和基本处理方式,通过这些知识点我们已经 ...
- 【转】Python之xml文档及配置文件处理(ElementTree模块、ConfigParser模块)
[转]Python之xml文档及配置文件处理(ElementTree模块.ConfigParser模块) 本节内容 前言 XML处理模块 ConfigParser/configparser模块 总结 ...
- ZH奶酪:Python使用ElementTree解析XML【译】
19.7. xml.etree.ElementTree — The ElementTree XML API 源代码: Lib/xml/etree/ElementTree.py Element类型是一种 ...
- ElementTree之Xml文档处理
ElementTree: 表示整个XML层级结构 Element: 表示树形结构中所有的父节点 SubElement: 表示树形结构中所有的子节点 有些节点既是父节点,又是子节点 下面来看下这两个类的 ...
- Selenium Xpath Tutorials - Identifying xpath for element with examples to use in selenium
Xpath in selenium is close to must required. XPath is element locator and you need to provide xpath ...
- python xml.etree ElementTree解析 编辑 xml
python有很多种xml解析方式,不过感觉etree的ElementTree 用起来最方便. #coding=utf-8 from xml.etree import ElementTree impo ...
- Clone table header and set as the first element, and replace header's th with td
Clone table header and replace header's th with td var tableHeaderRow = '#tableId tbody tr:nth-child ...
- DOM中的node与element的区别
先看document的两个常见method. document.createTextNode Constructor: Text document.createElement Constructor: ...
随机推荐
- 华夏部分互联网科技公司创始及IPO信息
时间:2018-04-19 前面整理了一些美国科技公司的信息,这篇文章整理的是我华夏的一些科技公司的信息. 华为.百度.阿里.腾讯.美团.携程.京东.小米.奇虎360……之后,其它一些公司,要么体量 ...
- handlermethodargumentresolver
http://www.cnblogs.com/fangjian0423/p/springMVC-request-param-analysis.html http://www.cnblogs.com/f ...
- JavaScript数据检测
前言: 随着编程实践的增加,慢慢发现关于数据类型的检测至关重要.我认为程序就是为了处理数据和展示数据.所以,数据的检测对于编程来说也至关重要.因为只有符合我们预期的输入,才可能产生正确的输出.众所周知 ...
- SQL农历转换函数(显示中文格式,加入润月的显示)
if object_id('fn_getlunar') is not null drop function fn_getlunar go create function dbo.fn_getlunar ...
- 如何验证一个地址可否使用—— MmIsAddressValid函数分析
又是一篇内核函数分析的博文,我个人觉得Windows的内核是最好的老师,当你想实现一个功能之前可以看看Windows内核是怎么做的,说不定就有灵感呢:) 首先看下官方的注释说明: /*++ Routi ...
- Azkaban(二)CentOS7.5安装Azkaban
1.软件介绍 Azkaban Web 服务器:azkaban-web-server-2.5.0.tar.gz Azkaban Excutor 执行服务器:azkaban-executor-server ...
- Action(8):Error-26608:HTTP Status-Code=504(Gateway Time-out)
Action(8):Error-26608:HTTP Status-Code=504(Gateway Time-out) 若出现如下图问题, 1.在Vuser Generator中的Tools---& ...
- Linux 下开发环境的搭建(软件安装)
一.Centos6.5下安装JDK 步骤1: 查看现有安装的JDK版本 rpm –qa | grep -i java 步骤2: 卸载已有软件 rpm -e --nodeps java-1.7.0-op ...
- thinkphp中I()方法的详解
I('post.email','','email'); int boolean float validate_regexp validate_url validate_email validate_i ...
- PHP的单引号和双引号
单引号内部的变量不会执行,双引号会执行. <?php $name = 'hello php'; echo "<h1>$name</h1>"; echo ...