0
進出口試圖除去所有兄弟姐妹給定的元素:刪除元素的兄弟姐妹在python
例如,給定此etree對象
<xml>
<letter name="A">
<letter name="B">
<letter name="C">
</letter>
<letter name="D">
</letter>
<letter name="G">
</letter>
<letter name="H">
</letter>
<letter name="I">
</letter>
</letter>
<letter name="E">
<letter name="F">
</letter>
</letter>
</letter>
</xml>
我想刪除全部G節點的兄弟姐妹和返回此:
<xml>
<letter name="A">
<letter name="B">
<letter name="G">
</letter>
</letter>
<letter name="E">
<letter name="F">
</letter>
</letter>
</letter>
</xml>
不使用xpath或找到,以迭代的方式。
你能提供一些關於如何做的建議嗎?
這是我只寫
import xml.etree.ElementTree as etree
data = """
<xml>
<letter name="A">
<letter name="B">
<letter name="C">
</letter>
<letter name="D">
</letter>
<letter name="G">
</letter>
<letter name="H">
</letter>
<letter name="I">
</letter>
</letter>
<letter name="E">
<letter name="F">
</letter>
</letter>
</letter>
</xml>
"""
tree =etree.fromstring(data)
for parent in tree.getiterator():
for child in parent:
for subchild in child:
if subchild.attrib.get('name') == "G":
parent_name = child.attrib.get('name')
#print parent_name
for parent in tree.getiterator():
if parent.attrib.get('name') == parent_name:
for child in parent:
if child.attrib.get('name') == "G":
print "not this"
else:
parent.remove(child)
print etree.tostring(tree)
乾杯代碼!
你可以分享你已經嘗試過的任何代碼嗎? –
不使用xpath?爲什麼? – roippi
任何幫助@JustinBarber ?? – ccamacho