无法保留使用ElementTree处理的xml的原始顺序

时间:2015-07-23 12:23:12

标签: python xml elementtree

目标是处理最初的xml文件:

<?xml version="1.0" encoding="utf-8"?>

<model name="cluster">
    <data>
        <datum name="name1"  set="no" get="yes" priority="yes" type="integer" description="desc. for name 1"/>
        <datum name="name2"  set="no" get="yes" priority="yes" type="integer" description="desc. for name 2"/>
        <datum name="name3"  set="no" get="yes"                type="integer" description="desc. for name 3"/>
        <datum name="name4"  set="no" get="yes"                type="integer" description="desc. for name 4"/>
        <datum name="name5"  set="no" get="yes" priority="yes" type="integer" description="desc. for name 5"/>
        <datum name="name6"  set="no" get="yes" priority="yes" type="string"  description="desc. for name 6"/>
</data>

检查状态并填充缺少的优先级属性。 为此,我使用了如下的elementTree:

def validate_file(filename):
    tree = ET.parse(filename)
    root=tree.getroot()
    for x in root.findall('data'):
        datum= x.find('datum')
        name= datum.get('name')
    for name in root.iter('datum'):
        priority = name.get('priority')        
        if not priority :
            name.set('priority', 'yes')            
    tree.write('myfile.xml')

问题是elementTree总是对处理过的元素进行排序,因此输入文件的结尾为:

<model name="cluster">
        <data>
            <datum description="desc. for name 1" get="yes" name="name1"  priority="yes" set="no"   type="integer" />
            <datum description="desc. for name 2" get="yes" name="name2"  priority="yes" set="no"   type="integer" />
            <datum description="desc. for name 3" get="yes" name="name3"  priority="yes" set="no"   type="integer" />
            <datum description="desc. for name 4" get="yes" name="name4"  priority="yes" set="no"   type="integer" />
            <datum description="desc. for name 5" get="yes" name="name5"  priority="yes" set="no"   type="integer" />
            <datum description="desc. for name 6" get="yes" name="name6"  priority="yes" set="no"   type="string" />            
    </data>
</model>

按字母顺序排列,原始文件不是。 由于此处已发布similar question,我无法相信能够拥有相同的原始订单,需要修改(即:patch)elementTree源代码。 最后,如果ElementTree无法做到这一点:是否有一种解决方法可以保持相同的顺序,因为人们更容易阅读它?

0 个答案:

没有答案