如何从配置文件中读取XML格式的值,如下所示。标签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>
答案 0 :(得分:0)
您可以使用标准库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'}
答案 1 :(得分:0)
我认为这样更好。
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