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(转)的更多相关文章

  1. Element DOM Tree jQuery plugin – Firebug like functionality | RockingCode

    Element DOM Tree jQuery plugin – Firebug like functionality | RockingCode Element DOM Tree jQuery pl ...

  2. Python之xml文档及配置文件处理(ElementTree模块、ConfigParser模块)

    本节内容 前言 XML处理模块 ConfigParser/configparser模块 总结 一.前言 我们在<中我们描述了Python数据持久化的大体概念和基本处理方式,通过这些知识点我们已经 ...

  3. 【转】Python之xml文档及配置文件处理(ElementTree模块、ConfigParser模块)

    [转]Python之xml文档及配置文件处理(ElementTree模块.ConfigParser模块) 本节内容 前言 XML处理模块 ConfigParser/configparser模块 总结 ...

  4. ZH奶酪:Python使用ElementTree解析XML【译】

    19.7. xml.etree.ElementTree — The ElementTree XML API 源代码: Lib/xml/etree/ElementTree.py Element类型是一种 ...

  5. ElementTree之Xml文档处理

    ElementTree: 表示整个XML层级结构 Element: 表示树形结构中所有的父节点 SubElement: 表示树形结构中所有的子节点 有些节点既是父节点,又是子节点 下面来看下这两个类的 ...

  6. 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 ...

  7. python xml.etree ElementTree解析 编辑 xml

    python有很多种xml解析方式,不过感觉etree的ElementTree 用起来最方便. #coding=utf-8 from xml.etree import ElementTree impo ...

  8. 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 ...

  9. DOM中的node与element的区别

    先看document的两个常见method. document.createTextNode Constructor: Text document.createElement Constructor: ...

随机推荐

  1. CentOS7 修改网卡名称

    vi /etc/sysconfig/grub 增加net.ifnames=0 biosdevname=0 执行:grub2-mkconfig -o /boot/grub2/grub.cfg

  2. 使用PyMongo访问需要认证的MongoDB

    Windows 10家庭中文版,Python 3.6.4,PyMongo 3.7.0,MongoDB 3.6.3,Scrapy 1.5.0, 前言 在Python中,使用PyMongo访问Mongod ...

  3. Flask:abort()函数

    Windows 10家庭中文版,Python 3.6.4,Flask 1.0.2 abort()函数用于提前退出(Google翻译abort)一个请求,并用指定的错误码返回. 函数原型如下: flas ...

  4. 基于timestamp和nonce的防止重放攻击方案

    参考:http://blog.csdn.net/koastal/article/details/53456696

  5. 前端打包工具之fis3的初级使用

    说到打包工具,大家都会想到webpack,我之前也接触过webpack,说实话个人觉得webpack上手容易,但是对于新手来说里面有太多坑,配置文件也不简单.于是乎,我转入了fis3阵营,发现fis3 ...

  6. win10 操作配置备忘

    让程序自动启动 如果想要实现应用程序在所有的用户登录系统后都能自动启动,就把该应用程序的快捷方式放到"系统启动文件夹"里: C:\ProgramData\Microsoft\Win ...

  7. js交互

    Js和native交互的方法与问题 实现JS和Native交互有两种方式: 第一种:shouldOverrideUrlLoading(WebView view, String url) 通过给WebV ...

  8. HBase(二)CentOS7.5搭建HBase1.2.6HA集群

    一.安装前提 1.HBase 依赖于 HDFS 做底层的数据存储 2.HBase 依赖于 MapReduce 做数据计算 3.HBase 依赖于 ZooKeeper 做服务协调 4.HBase源码是j ...

  9. JOIN从句

    MySQL基础表和数据 -- 5条数据 select * from test_a; -- 8条数据 select * from test_b; 内连接 -- 内连接,join,为inner join的 ...

  10. day7面向对象--反射

    反射 通过字符串映射或修改程序运行时的状态.属性.方法, 有以下4个方法     1.getattr(object, name[, default]) -> value Get a named ...