0

I want to load some tags with a specified order from an xml file into python as below:

<data>
    <testset name="ts1" order="1" descrption="this is ts1 descrption">
        <testcase name="tc1" order="1" />
        <testcase name="tc2" order="2" />
    </testset>

    <testset name="ts2" order="2" descrption="this is ts2 descrption">
        <testcase name="tc3" order="1" />
        <testcase name="tc4" order="2" />
    </testset>
</data>

The way that I know is ugly so please let me know if there is a better way:

class TS():
    def __init__(self, name, order):
        self.name = name
        self.order = order

import xml.etree.ElementTree as ET
def parseXML():
    ts_arr = []
    tree = ET.parse('test_specs.xml')
    root = tree.getroot()
    for testset in root.iter('testset'):
        i = 0
        while i<len(ts_arr):
            if testset.get('order')<ts_arr[i].order:
                        ts_arr.append(i, TS(testset.get('name'),testset.get('order')))
                        break
            i += 1

... and the same for testcases

1 Answer 1

1

Sort the test sets by their order attribute:

root = tree.getroot()
testsets = root.findall('testset')

for testset in sorted(testsets, key=lambda ts: int(ts.attrib['order'])):
    # test sets are looped over in the order specified in the `order` attributes
    testcases = testset.findall('testcase')
    for testcase in sorted(testcases, key=lambda ts: int(ts.attrib['order'])):
        # test cases are looped over in the order specified
Sign up to request clarification or add additional context in comments.

1 Comment

Wonderful. 100% bang on. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.