2013-04-17 62 views
1

我有一個看起來像這樣的XML文件。將XML轉換爲cfg文件

<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="show_batch" value="true" /> 
    <setting id="show_log" value="true" /> 
</settings> 

我想在XML上運行一個python腳本,它會將信息提取到cfg文件中。 所以它看起來像這樣。

auto_backup=false 
exitonbackspace=true 
nb_backupfiles=10 
refreshonload=true 
screen2=false 
show_batch=true 
show_log 

我該怎麼辦呢?

+1

你嘗試過什麼?用像lxml這樣的東西來解析它,然後從這裏簡單地進行解析。 – JosefAssad

回答

1
#!/usr/bin/env python2.7 

import sys, lxml.etree 

tree = lxml.etree.parse(sys.stdin) 

for el in tree.findall('setting'): 
    print el.attrib['id'], '=', el.attrib['value'] 

就像這樣。從標準輸入到輸出的轉換,所以你可以假設它是script.py

cat settings.xml | ./script.py >> settings.cfg 
+0

我需要它是自包含的,所以我可以運行它。可以使用'doc = etree.parse('settings.xml')'然後使用'foo = open('settings.cfg','w')'然後foo.write寫入文件來導入文件。我將如何與上述工作? – Syborg

+0

您可以根據自己的需要進行調整。放入你提到的行,並使用'foo.write('%s =%s \ n「%(el.attrib ['id'],el.attrib ['value']))''而不是打印。 – TNW

+0

得到它到底做了些什麼,此代碼'#!的/ usr/bin中/ env的python2.7 進口SYS,lxml.etree DOC = lxml.etree.parse( '的settings.xml') 富= ('setting'): foo.write(「%s =%s \ n」%(el.attrib ['id']) ,el.attrib ['value'])) foo.close()' – Syborg