Created
December 5, 2019 15:36
-
-
Save arnobaer/2ea26305d739320eab84da5da98bb2a1 to your computer and use it in GitHub Desktop.
Example in parsing XML menus
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Parsing XML menu to JSON | |
# | |
# Usage: | |
# python xml2json.py sample.xml | |
# | |
# Example data: | |
# https://raw.githubusercontent.com/cms-l1-globaltrigger/cms-l1-menu/master/2019/L1Menu_Collisions2018_v2_1_0-d2/xml/L1Menu_Collisions2018_v2_1_0-d2.xml | |
# | |
import json | |
import argparse | |
# Import DOM tree parser | |
import xml.etree.ElementTree as etree | |
parser = argparse.ArgumentParser() | |
parser.add_argument('filename') | |
args = parser.parse_args() | |
# Load XML file | |
with open(args.filename) as f: | |
tree = etree.parse(f) | |
# XPath queries to meta data | |
name = tree.findall('name')[0].text | |
uuid_menu = tree.findall('uuid_menu')[0].text | |
uuid_firmware = tree.findall('uuid_firmware')[0].text | |
grammar_version = tree.findall('grammar_version')[0].text | |
comment = tree.findall('comment')[0].text | |
# XPath queries to algorithms name and index | |
algorithms = [] | |
for el in tree.findall('algorithm'): | |
index = int(el.findall('index')[0].text) | |
name = el.findall('name')[0].text | |
algorithms.append(dict( | |
name=name, | |
index=index | |
)) | |
# Convert to JSON | |
data = json.dumps(dict( | |
name=name, | |
uuid_menu=uuid_menu, | |
uuid_firmware=uuid_firmware,, | |
grammar_version=grammar_version, | |
comment=comment, | |
algorithms=algorithms | |
)) | |
print(data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment