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. scrapy shell命令的【选项】简介

    在使用scrapy shell测试某网站时,其返回400 Bad Request,那么,更改User-Agent请求头信息再试. DEBUG: Crawled () <GET https://w ...

  2. 3.Springboot之修改启动时的默认图案Banner

    一.SpringBoot的默认启动图案 在SpringBoot启动的时候,默认的会展示出一个spring的logo,这个图案我们用户是可以自定义的 二.自定义启动图案 方法一: Application ...

  3. Android Studio配置opencv

    安装过程参考:http://www.cnblogs.com/tail/p/4618476.html demo参考:http://blog.csdn.net/gao_chun/article/detai ...

  4. Java多线程-Java多线程概述

    第一章 Java多线程概述 线程的启动 线程的暂停 线程的优先级 线程安全相关问题 1.1 进程与线程 进程:可以将运行在内存中的程序(如exe文件)理解为进程,进程是受操作系统管理的基本的运行单元. ...

  5. 日志、字段备注查询、自增ID联系设置、常用存储过程

    -----获取数据字典SQL(表字段说明)SELECT     [Table Name] = OBJECT_NAME(c.object_id),     [Column Name] = c.name, ...

  6. Struts 2 Tutorial

    Apache Struts 2 is an elegant, extensible framework for creating enterprise-ready Java web applicati ...

  7. 大数据统计分析平台之三、Kibana安装和使用

    kibana安装 1.到官网下载kibana: cd /usr/local/software wget https://artifacts.elastic.co/downloads/kibana/ki ...

  8. 如何把自己的wordpress网站移到本地修改

    有时候wordpress更换模板时,需要修改的地方很多,而且在线修改不是很好.只能把它移动到电脑本地进行修改了.这样修改好就可以直接套用到网站上了. 1.通过服务器控制面板或FTP整站打包,发送到你已 ...

  9. ***codeigniter操作xml(Simplexml第三方扩展)

    This Simplexml class provides an alternative implementation of the SimpleXML API that works under PH ...

  10. 关于URL编码(针对URL含有中文的参数)

    http://www.ruanyifeng.com/blog/2010/02/url_encoding.html 一.问题的由来 URL就是网址,只要上网,就一定会用到. 一般来说,URL只能使用英文 ...