Add xpath2json tool

Nice for local testing
This commit is contained in:
Peder Bergebakken Sundt 2022-11-20 00:39:04 +01:00
parent 51d821d500
commit 7af9b66a35
1 changed files with 27 additions and 0 deletions

27
xpath2json.py Executable file
View File

@ -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()