Python使用lxml模块xpath语句定位xml指定属性指定值节点的祖先节点
需求
是不是很绕口?看例子,我有如下结构xml文档:
<Placemark>
<Style>...</Style>
<ExtendData><SchemaData schemaUrl="xxxx">
<SimpleData name="ID">1234567890</SimpleData>
<SimpleData name="Color">FFFFFF</SimpleData>
<SimpleData name="Type">4</SimpleData>
</SchemaData></ExtendData>
</Placemark>
我想定位所有SimpleData属性Type值为4的祖先节点Placemark
实现
使用python的lxml模块执行xpath查询
使用连续[][]条件约束simpledata节点
定位Placemark用/../../..
可以但不优雅,无法应对节点层级变化
代码:
from lxml import etree
NS = {"I":"http://www.opengis.net/kml/2.2"}
file = "lines.kml"
tree = etree.parse(file)
root = tree.getroot()
cmData = root[0]
placemark = cmData.xpath(".//I:SimpleData[@name='Type'][.='4']/ancestor::I:Placemark",namespaces=NS)