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: ...
随机推荐
- 安装virtualenv(Scrapy)
Windows 10家庭中文版,Python 3.6.4, virtualenv用来提供一个应用程序独立的 运行环境,这个独立是相对于系统的Python运行环境而言,开发者可以在virtualenv建 ...
- new Function和eval区别
eval和new Function都可以动态解析和执行字符串.但是它们对解析内容的运行环境判定不同. eval中的代码执行时的作用域为当前作用域.它可以访问到函数中的局部变量. new Functio ...
- 【剑指Offer面试题】 九度OJ1389:变态跳楼梯
转自:http://www.myexception.cn/program/1973966.html 时间限制:1 秒内存限制:32 兆特殊判题:否提交:2331解决:1332 题目描述: 一只青蛙一次 ...
- GitHub在线创建文件夹
点击New files按钮,然后输入含有slash字符(“/”)的文件名即可.也就是建立一个含有路径(目录)的文件,即会自动产生新文件夹. 点击Upload files按钮,然后直接把本地的文件夹(内 ...
- Zabbix监控实例
本节内容: zabbix web添加主机 定义Items 创建graph 创建template 一.zabbix web添加主机 1. 进入zabbix web界面,点击配置—>主机—>创 ...
- Loadrunner参数化逗号报错解决方法
Loadrunner参数化逗号报错解决方法 介绍Loadrunner参数化时,参数中包含有逗号时出错的解决方法. 在Loadrunner进行参数化时,参数中如果含有逗号,编辑保存后会报错: 此 ...
- wampserver的安装和使用
首先想说一下通常搭建WAMP平台的时候主要分为散装包搭建和集成包搭建过程. 散装包搭建就是把PHP,Apache,MySQL等下载下来,一个个的安装,其过程灰常的复杂,而且需要配置的系统变量和修改的文 ...
- 黑马程序员_java基础笔记(09)...HTML基本知识、CSS、JavaScript、DOM
—————————— ASP.Net+Android+IOS开发..Net培训.期待与您交流! —————————— 基本标签(a.p.img.li.table.div.span).表单标签.ifra ...
- 再议js的传递和深复制
病理 基本类型的传递就是按值传递,比如说 var a = 1; var b = a; b = 3; console.log(a,b);//1,3 很明显,a的值并未因为b的值改变而变化,这是因为a只是 ...
- Oracle数据库多表查询,子查询,集合运算
记得自己要敲o~~~ select * from bonus; select * from salgrade; from dual; --笛卡尔积:两张表的乘积 select * from emp,d ...