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. 【小程序开发总结】微信小程序开发常用技术方法总结

    1.获取input的值 <input bindinput="bindKeyInput" placeholder="输入同步到view中"/>   b ...

  2. 【前端】上拉加载更多dropload.min.js的使用

    代码如下:入职代码修改接口及html为自己的即可(下面主要展示js部分) <!DOCTYPE html><html> <head> <meta charset ...

  3. html-示例代码

    <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/html" xml ...

  4. align="absmiddle" 的意义

    align=absmiddle表示图像的中间与同一行中最大元素的中间对齐 AbsBottom 图像的下边缘与同一行中最大元素的下边缘对齐. AbsMiddle   图像的中间与同一行中最大元素的中间对 ...

  5. invalid byte sequence for encoding "UTF8": 0xe99d2c

    服务器还原数据库数据出错,老规矩... 字符集编码的问题 http://blog.csdn.net/beiigang/article/details/39582583 over....

  6. OpenCV与Python之图像的读入与显示以及利用Numpy的图像转换

    1:读入图像,显示图像与保存图像 代码: import cv2 img=cv2.imread('lena.jpg',cv2.IMREAD_COLOR) cv2.namedWindow('lena',c ...

  7. 通过field:global给子元素添加css样式

    {dede:arclist row=5 typeid=200} <li [field:global runphp=’yes’ name=autoindex](@me==1)?@me=”class ...

  8. python 统计MySQL表信息

    一.场景描述 线上有一台MySQL服务器,里面有几十个数据库,每个库有N多表. 现在需要将每个表的信息,统计到excel中,格式如下: 库名 表名 表说明 建表语句 db1 users 用户表 CRE ...

  9. C++ "multiple definition of .. first defined here"

    C++ "multiple definition of .. first defined here" 在C++中,有时候需要在不同文件中使用同一个变量.对于这类变量如果处理不当,很 ...

  10. 浅谈C#中的模式窗体和非模式窗体

    ShowDialog(); // 模式窗体 Show(); // 非模式窗体 区别: 返回值不同,DialogResult/void 模式窗体会使程序中断,直到关闭模式窗口 打开模式窗体后不能切换到应 ...