将解析的XML文件排序为cfg文件

时间:2013-04-19 00:02:50

标签: python python-2.x

我正在使用此代码将XML文件转换为cfg文件

import sys, lxml.etree

doc = lxml.etree.parse('settings.xml')

foo = open('settings.cfg', 'w')

for el in doc.findall('setting'):
    foo.write("%s=%s\n" % (el.attrib['id'], el.attrib['value']))
foo.close() 

有没有办法在将标签写入文件之前对标签进行排序,也可能忽略某些标签。

输入

<settings>
    <setting id="auto_backup" value="false" />
    <setting id="exitonbackspace" value="true" />
    <setting id="hidemousepointer" value="true" />
    <setting id="nb_backup_files" value="10" />
    <setting id="refreshonload" value="true" />
    <setting id="screen2" value="false" />
    <setting id="separator" value="" />
    <setting id="show_batch" value="true" />
    <setting id="show_log" value="true" />
</settings>

当前输出

auto_backup=false
exitonbackspace=true
hidemousepointer=true
nb_backup_files=10
refreshonload=true
screen2=false   
separator=
show_batch=true
show_log=true

需要输出

exitonbackspace=true
screen2=true
refreshonload=true
hidemousepointer=false

2 个答案:

答案 0 :(得分:1)

为xml中找到的所有设置标记创建字典settings_dict

为您希望设置显示的顺序创建一个列表settings_order

遍历settings_order,如果settings_dict中有元素,则可以输出。

import sys

try:
    from lxml import etree
except:
    import xml.etree.cElementTree as etree

doc = etree.parse('settings.xml')

settings_dict = dict([(el.attrib['id'], el) for el in doc.findall('setting')])
settings_order = ['exitonbackspace','screen2', 'refreshonload', 'hidemousepointer']

foo = open('settings.cfg', 'w')
for setting_id in settings_order:
    if setting_id in settings_dict:
        el = settings_dict[setting_id]
        foo.write("%s=%s\n" % (el.attrib['id'], el.attrib['value']))
foo.close()

答案 1 :(得分:0)

  

当前输出

     

需要输出

嗯...您的输入和当前输出似乎按ID排序,您的'require'输出似乎是随机的。那么如何对输入进行排序以达到您的需求输出?我们需要安装mindreader模块吗?

如果您的输入如下:

<settings>
    <setting id="hidemousepointer" value="true" />
    <setting id="show_batch" value="true" />
    <setting id="nb_backup_files" value="10" />
    <setting id="refreshonload" value="true" />
    <setting id="exitonbackspace" value="true" />
    <setting id="screen2" value="false" />
    <setting id="separator" value="" />
    <setting id="auto_backup" value="false" />
    <setting id="show_log" value="true" />
</settings>

您可以按ID进行排序:

import sys, lxml.etree

doc = lxml.etree.parse('settings.xml')

elements = doc.findall('setting');
sorted_elmts = sorted(elements, key=lambda elmt: elmt.attrib['id']);

for el in sorted_elmts:
    attribs = el.attrib
    print("%s=%s" % (attribs['id'], attribs['value']))

--output:--
auto_backup=false
exitonbackspace=true
hidemousepointer=true
nb_backup_files=10
refreshonload=true
screen2=false
separator=
show_batch=true
show_log=true