排序一个解析XML文件到CFG文件
问题描述:
我使用这个代码把一个XML文件转换为CFG文件排序一个解析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
答
创建一个字典,settings_dict
,在XML中找到的所有设置标签。
通过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()
答
电流输出
要求输出
Uhmm ...您的输入和输出电流似乎是由ID进行排序,你的 '需要' 输出似乎是随机的。那么如何将您的输入分类以达到您的要求输出?我们是否需要安装mindreader模块?
如果你的输入是这样的:
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
:
<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进行排序