Skip to main content
 首页 » 编程设计

python之合并 XML 文件类似于 ConfigParser 的多文件支持

2025年05月04日8soundcode

我正在编写一个在其文件中使用 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 完成。我该如何实现?

请您参考如下方法:

您可以将 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'}