必须删除除一个之外的所有子元素(SimpleData name =“NAME”)。
所以我想保留。
<Placemark>
<Style><LineStyle><color>ff0000ff</color></LineStyle><PolyStyle><fill>0</fill></PolyStyle></Style>
<ExtendedData><SchemaData schemaUrl="#osa_20140910_areas">
<SimpleData name="gml_id">219</SimpleData>
<SimpleData name="ID">219</SimpleData>
<SimpleData name="CODE">520</SimpleData>
<SimpleData name="DISTRICT">102</SimpleData>
<SimpleData name="STOR_DISTRICT">1</SimpleData>
<SimpleData name="COUNTY">91</SimpleData>
<SimpleData name="WHOLE_CODE">911102520.000000000000000</SimpleData>
<SimpleData name="NAME">Calgary</SimpleData>
</SchemaData></ExtendedData>
感谢任何帮助。
答案 0 :(得分:1)
您可以使用lxml中的Element.remove()
删除单个元素。
from lxml import etree
tree = etree.XML('''<Placemark>
<Style><LineStyle><color>ff0000ff</color></LineStyle><PolyStyle><fill>0</fill></PolyStyle></Style>
<ExtendedData><SchemaData schemaUrl="#osa_20140910_areas">
<SimpleData name="gml_id">219</SimpleData>
<SimpleData name="ID">219</SimpleData>
<SimpleData name="CODE">520</SimpleData>
<SimpleData name="DISTRICT">102</SimpleData>
<SimpleData name="STOR_DISTRICT">1</SimpleData>
<SimpleData name="COUNTY">91</SimpleData>
<SimpleData name="WHOLE_CODE">911102520.000000000000000</SimpleData>
<SimpleData name="NAME">Calgary</SimpleData>
</SchemaData></ExtendedData>
</Placemark>''')
print tree
for simple_data in tree.xpath('//SimpleData[@name!="NAME"]'):
simple_data.getparent().remove(simple_data)
print etree.tostring(tree)