You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

44 lines
1.1 KiB

  1. #! /usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import json
  4. import sys
  5. import argparse
  6. parser = argparse.ArgumentParser(description='Convert an XML file to JSON.')
  7. parser.add_argument('--unsafe', action='store_true',
  8. help='do not use defusedxml: only for known-safe XML!')
  9. parser.add_argument('infile', nargs='?', type=argparse.FileType('rt'),
  10. default=sys.stdin)
  11. def xml_element_to_dict(elem):
  12. "Convert XML Element to a simple dict"
  13. inner = dict(elem.attrib)
  14. children = list(map(xml_element_to_dict, list(elem)))
  15. text = elem.text and elem.text.strip()
  16. if text:
  17. inner['@text'] = text
  18. if children:
  19. inner['@children'] = children
  20. return {elem.tag: inner}
  21. def main(args):
  22. "Dump JSON-from-parsed-XML to stdout"
  23. if args.unsafe:
  24. import xml.etree.ElementTree as ElementTree
  25. # import defusedxml.ElementTree as ElementTree
  26. xml_parser = ElementTree.parse(args.infile)
  27. root = xml_parser.getroot()
  28. json.dump(xml_element_to_dict(root), sys.stdout, indent=2)
  29. print()
  30. if __name__ == '__main__':
  31. args = parser.parse_args()
  32. main(args)