मुझे एक विशेषता की सामग्री के आधार पर तत्वों को पूरी तरह से हटाने की आवश्यकता है, अजगर के एलएक्सएमएल का उपयोग करके। उदाहरण:
import lxml.etree as et
xml="""
<groceries>
<fruit state="rotten">apple</fruit>
<fruit state="fresh">pear</fruit>
<fruit state="fresh">starfruit</fruit>
<fruit state="rotten">mango</fruit>
<fruit state="fresh">peach</fruit>
</groceries>
"""
tree=et.fromstring(xml)
for bad in tree.xpath("//fruit[@state=\'rotten\']"):
#remove this element from the tree
print et.tostring(tree, pretty_print=True)
मैं यह प्रिंट करना चाहूंगा:
<groceries>
<fruit state="fresh">pear</fruit>
<fruit state="fresh">starfruit</fruit>
<fruit state="fresh">peach</fruit>
</groceries>
क्या एक अस्थायी चर को संचय किए बिना ऐसा करने का एक तरीका है और इसे मैन्युअल रूप से मुद्रित करना है, जैसे:
newxml="<groceries>\n"
for elt in tree.xpath('//fruit[@state=\'fresh\']'):
newxml+=et.tostring(elt)
newxml+="</groceries>"