Created
January 28, 2015 15:47
-
-
Save stevedoyle/b9c306f0866ff5366581 to your computer and use it in GitHub Desktop.
Remove a node from an XML tree using lxml objectify and xpath
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from StringIO import StringIO | |
from lxml import objectify | |
class SampleParser: | |
def __init__(self, xml_data): | |
tree = objectify.parse(xml_data) | |
self.root = tree.getroot() | |
def student_names(self): | |
return [name.text for name in self.root.xpath('//Student/name')] | |
def remove_student(self, student_name): | |
students = [name.getparent() for name in self.root.xpath('//Student/name') if name.text == student_name] | |
for student in students: | |
student.getparent().remove(student) | |
if __name__ == "__main__": | |
student_xml = """ | |
<Students> | |
<Student> | |
<name>Bob</name> | |
</Student> | |
<Student> | |
<name>Alice</name> | |
</Student> | |
<Student> | |
<name>Stephen</name> | |
</Student> | |
<Student> | |
<name>Alice</name> | |
</Student> | |
</Students>""" | |
parser = SampleParser(StringIO(student_xml)) | |
print(', '.join(parser.student_names())) | |
parser.remove_student('Alice') | |
print(', '.join(parser.student_names())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment