在python中按特定顺序解析xml标记

时间:2013-06-07 23:01:13

标签: python xml parsing

我想将一些带有指定顺序的标签从xml文件加载到python中,如下所示:

<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>

我知道的方式很难看,所以请告诉我是否有更好的方法:

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

...和测试用例相同

1 个答案:

答案 0 :(得分:1)

按照订单属性对测试集进行排序:

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