Skip to content

Instantly share code, notes, and snippets.

@haxxinen
Last active February 15, 2020 16:03
Show Gist options
  • Save haxxinen/8e94bad30b0b4eb467dfb9378620b6ba to your computer and use it in GitHub Desktop.
Save haxxinen/8e94bad30b0b4eb467dfb9378620b6ba to your computer and use it in GitHub Desktop.
File: /tmp/elements.xml
<?xml version="1.0"?>
<elements>
    <parent name="A">
        <child value="a"></child>
        <child value="b"></child>
    </parent>
    <parent name="B">
        <child value="c"></child>
        <child value="d"></child>
    </parent>
</elements>
File: /tmp/xpath_example.py
#!/usr/bin/python
import libxml2
#$ sudo apt-get install python3-libxml2

doc = libxml2.parseFile('/tmp/elements.xml')

# get values of all children based on their parent
def valuesOfParent(parent_name):
    r = doc.xpathEval('//parent[@name="' + parent_name + '"]/child/@value')
    for i in r:
        print(i.content)

valuesOfParent('A')
valuesOfParent('B')
Running the script
$ python3 /tmp/xpath_example.py
a
b
c
d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment