-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathxml2xpath.py
More file actions
32 lines (27 loc) · 1.1 KB
/
xml2xpath.py
File metadata and controls
32 lines (27 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import argparse
import sys
import libxml2
def main():
parser = argparse.ArgumentParser(
prog='xmlxpath',
description='Run an xpath expression on an XML file',
epilog='Example: xmlxpath --ns="foo=http://example.com/foo" --ns="bar=http://another.com/bar" --xpath="//foo:node/bar:node[@attrib=\'value\']" < infile > outfile')
parser.add_argument('--xpath', required=True, type=str, help='The xpath expression, supporting the xml.etree.ElementTree subset')
parser.add_argument('--ns', required=False, action='append', type=str, help='(optional) Namespace declaration(s), as "alias=URI"')
args = parser.parse_args()
xmlfile = libxml2.parseDoc(sys.stdin.read())
context = xmlfile.xpathNewContext()
if args.ns:
for ns in args.ns:
alias, uri = ns.split('=', 1)
context.xpathRegisterNs(alias, uri)
results = context.xpathEval(args.xpath)
if results:
for result in results:
print(result.getContent())
context.xpathFreeContext()
xmlfile.freeDoc()
if not results:
exit(1)
if __name__ == "__main__":
main()