如何使用 python 在 xml formate 中读取配置文件
how to read config file in xml formate using python
如何从 XML 格式的配置文件中读取值 below.here 标签 name1、name2 将增加,如 name4、name5...
<config>
<name>
<name1>xxxxxxxxx</name1>
<name2>yyyyyyyyy</name2>
<name3>zzzzzzzzz</name3>
</name>
<company>
<loc1>1234</loc1>
<loc2>1242</loc2>
<loc3>1212</loc3>
</company>
</config>
您可以使用标准库 xml
包来解析 xml 文档。
例如:
In [91]: import xml.etree.ElementTree as ET
In [92]: data = """
...: <config>
...: <name>
...: <name1>xxxxxxxxx</name1>
...: <name2>yyyyyyyyy</name2>
...: <name3>zzzzzzzzz</name3>
...: </name>
...: <company>
...: <loc1>1234</loc1>
...: <loc2>1242</loc2>
...: <loc3>1212</loc3>
...: </company>
...: </config>
...: """
In [93]:
In [93]: x = ET.fromstring(data)
In [94]: [each.text for each in x.find('.//name')]
Out[94]: ['xxxxxxxxx', 'yyyyyyyyy', 'zzzzzzzzz']
或者如果你想要一本字典:
In [95]: {each.tag:each.text for each in x.find('.//name')}
Out[95]: {'name1': 'xxxxxxxxx', 'name2': 'yyyyyyyyy', 'name3': 'zzzzzzzzz'}
我觉得这样更好
import xml.dom.minidom as minidom
dic={}
dom = minidom.parse("filename")
root = dom.documentElement #take name1 as example
dic['name1']=root.getElementsByTagName('name1')[0].firstChild.data
如何从 XML 格式的配置文件中读取值 below.here 标签 name1、name2 将增加,如 name4、name5...
<config>
<name>
<name1>xxxxxxxxx</name1>
<name2>yyyyyyyyy</name2>
<name3>zzzzzzzzz</name3>
</name>
<company>
<loc1>1234</loc1>
<loc2>1242</loc2>
<loc3>1212</loc3>
</company>
</config>
您可以使用标准库 xml
包来解析 xml 文档。
例如:
In [91]: import xml.etree.ElementTree as ET
In [92]: data = """
...: <config>
...: <name>
...: <name1>xxxxxxxxx</name1>
...: <name2>yyyyyyyyy</name2>
...: <name3>zzzzzzzzz</name3>
...: </name>
...: <company>
...: <loc1>1234</loc1>
...: <loc2>1242</loc2>
...: <loc3>1212</loc3>
...: </company>
...: </config>
...: """
In [93]:
In [93]: x = ET.fromstring(data)
In [94]: [each.text for each in x.find('.//name')]
Out[94]: ['xxxxxxxxx', 'yyyyyyyyy', 'zzzzzzzzz']
或者如果你想要一本字典:
In [95]: {each.tag:each.text for each in x.find('.//name')}
Out[95]: {'name1': 'xxxxxxxxx', 'name2': 'yyyyyyyyy', 'name3': 'zzzzzzzzz'}
我觉得这样更好
import xml.dom.minidom as minidom
dic={}
dom = minidom.parse("filename")
root = dom.documentElement #take name1 as example
dic['name1']=root.getElementsByTagName('name1')[0].firstChild.data