结合类似于ConfigParser的多文件支持的XML文件

时间:2011-10-07 09:04:22

标签: python xml configuration-files

我正在编写一个在其文件中使用XML的应用程序配置模块。请考虑以下示例:

<?xml version="1.0" encoding="UTF-8"?>
<Settings>
    <PathA>/Some/path/to/directory</PathA>
    <PathB>/Another/path</PathB>
</Settings>

现在,我想覆盖之后加载的不同文件中的某些元素。覆盖文件的示例:

<?xml version="1.0" encoding="UTF-8"?>
<Settings>
    <PathB>/Change/this/path</PathB>
</Settings>

使用XPath查询文档(使用覆盖)时,我想将其作为元素树:

<?xml version="1.0" encoding="UTF-8"?>
<Settings>
    <PathA>/Some/path/to/directory</PathA>
    <PathB>/Change/this/path</PathB>
</Settings>

这与Python的ConfigParser使用read()方法所做的类似,但是使用XML完成。我该如何实现呢?

2 个答案:

答案 0 :(得分:1)

您可以将XML转换为Python类的实例:

import lxml.etree as ET
import io

class Settings(object):
    def __init__(self,text):
        root=ET.parse(io.BytesIO(text)).getroot()
        self.settings=dict((elt.tag,elt.text) for elt in root.xpath('/Settings/*'))
    def update(self,other):
        self.settings.update(other.settings)

text='''\
<?xml version="1.0" encoding="UTF-8"?>
<Settings>
    <PathA>/Some/path/to/directory</PathA>
    <PathB>/Another/path</PathB>
</Settings>'''

text2='''\
<?xml version="1.0" encoding="UTF-8"?>
<Settings>
    <PathB>/Change/this/path</PathB>
</Settings>'''    

s=Settings(text)
s2=Settings(text2)
s.update(s2)
print(s.settings)

产量

{'PathB': '/Change/this/path', 'PathA': '/Some/path/to/directory'}

答案 1 :(得分:0)

你必须使用XML吗?使用JSON更简单可以实现同样的目的: 假设这是第一个配置文件中的文本:

text='''
{
  "PathB": "/Another/path", 
  "PathA": "/Some/path/to/directory"
}
'''

这是第二个文本:

text2='''{
  "PathB": "/Change/this/path"
}'''

然后要合并到,您只需将每个加载到dict,然后调用update

import json
config=json.loads(text)
config2=json.loads(text2)
config.update(config2)
print(config)

产生Python dict

{u'PathB': u'/Change/this/path', u'PathA': u'/Some/path/to/directory'}
相关问题