How to manipulate Xpath multiple Condition queries using Python into a dictionary format?

Viewed 42

I have some strings of XML operator queries that I want to manipulate using Python and perform the actions mentioned in it. Now, these are some samples of strings:

../example-x = 'x' and ../example-y != 'y'
../example-x = 'x' or ../example-y != 'y'

Now, these above strings of XML queries, I was able to parse using below line of code in Python:

temp_output = {}
if len(re.split(' and| or', test)) > 1:
    and_or_condition = re.split(' and| or', test)
    condition = 'and' if ' and' in test else 'or'
    temp_output.update({condition: []})
    for i in and_or_condition:
        temp_condition = [i.strip('\n').strip(' ') for i in re.split('!=|=', i)]
        temp_condition[1] = re.sub('\'|"', '', temp_condition[1])
        if '!=' in i:
            temp_output[condition].append({temp_condition[0]: '!{}'.format(temp_condition[1])})
        else:
            temp_output[condition].append({temp_condition[0]: '{}'.format(temp_condition[1])})
print(temp_output)

And this gives me output with the above examples, which is the expected output:

{'and': [{'../example-x': 'x'}, {'../example-y': '!y'}]}
{'or': [{'../example-x': 'x'}, {'../example-y': '!y'}]}

Now, there are some scenarios where the both "and" and "or" will be present in the string like this:

(../example-x = 'x' and (../example-y != 'y' or ../example-z != 'z'))
(../example-x = 'x' or (../example-y != 'y' and ../example-z != 'z'))

Now, with this scenario, I am kind of confused about how to approach this especially on how to find out the outer/inner condition queries. The expected output string should be like this:

{'and': [{'../example-x': 'x'}, {'or': [{'../example-y': '!y'}, {'../example-z': '!z'}]]}}
{'or': [{'../example-x': 'x'}, {'and': [{'../example-y': '!y'}, {'../example-z': '!z'}]]}}

Kindly guide me on how to approach this problem.

0 Answers
Related