From 7af9b66a359207c4aa81cc04db9f7a06bcd8ccc2 Mon Sep 17 00:00:00 2001 From: Peder Bergebakken Sundt Date: Sun, 20 Nov 2022 00:39:04 +0100 Subject: [PATCH] Add xpath2json tool Nice for local testing --- xpath2json.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100755 xpath2json.py diff --git a/xpath2json.py b/xpath2json.py new file mode 100755 index 0000000..d03b88f --- /dev/null +++ b/xpath2json.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python3 +import sys, rich, libxml2 + +if len(sys.argv) < 3: + print(f"Usage: {sys.argv[0]} XML_FILENAME XPATH", file=sys.stderr) + exit() + +try: + doc = libxml2.parseFile(sys.argv[1]) + ctxt = doc.xpathNewContext() + res = ctxt.xpathEval(sys.argv[2]) + + out = [ + dict( + node = None if i.name in ("text", sys.argv[1]) else i.name, + xpath = i.nodePath(), + data = i.content, + content = i.content, # /shrug + attributes = {child.name: child.content for child in i.properties} if i.properties is not None else {}, + ) + for e, i in enumerate(res) + ] + rich.print_json(data=out) + +finally: + doc.freeDoc() + ctxt.xpathFreeContext()