28 lines
750 B
Python
Executable File
28 lines
750 B
Python
Executable File
#!/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()
|