1. 程式人生 > 實用技巧 >Python使用lxml模組xpath語句定位xml指定屬性指定值節點的制定名稱祖先節點

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)