Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 14040

To print the data after replacing the given expression with the values in XML file using "ElementTree" library

$
0
0

Given XML file snippet is:

<?xml version="1.0" standalone="yes"?><event_configuration family="21" version="2"><pqr subtype="abc"><event val="73002" name="$MyCpu"> </event><event val="73003" name="$MyCpuKernel"> </event><metric name="Ratio" expression="$MyCpuKernel / $MyCpu"> </metric></pqr></event_configuration>

I have parsed this xml file using "ElementTree" library in Python, please find the code below:

    def parse_xml_to_json(self):        data = {'metric': []}        root = ET.fromstring(self.xml_file)        for element in root.findall('.//*'):            element_type = element.tag            if element_type not in ["pqr", "stu", "vwx"]:                continue            subtype_name = element.attrib['subtype']            event_map = {}            for event in element.findall('.//event'):                event_name = event.attrib['name']                val_value = event.attrib['val']                event_map[event_name] = val_value            for metric in element.findall('metric'):                expression = metric.attrib['expression']                metric_name = metric.attrib['name']                for event_name, val_value in event_map.items():                    expression = expression.replace(event_name, val_value)                data['metric'].append({'Name': metric_name,'Expression': expression,'Type': element_type                })        return data

I am getting the output, but this code is unable to replace the event name present inside "Expression" with the val_value as shown below:-

Output:

{"metric": [    {"Name": "Ratio","Expression": "73002Kernel / 73002","Type": "pqr"    },    ....    ....]}

Here, we can see in the "Expression" it should print "73003 / 73002".I am unable to think of how to solve this issue. Is it possible to use regex here, how to apply it? Please suggest.


Viewing all articles
Browse latest Browse all 14040

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>