Search code examples
pythonxmlpython-3.xparsingconfiguration-files

how to read config file in xml formate using python


How to read the values from the config file which is in XML format looks below.here the tags name1,name2 will increase like 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>

Solution

  • You can use the standard library xml package to parse an xml document.

    For example:

    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']
    

    Or if you want a dictionary:

    In [95]: {each.tag:each.text for each in x.find('.//name')}
    Out[95]: {'name1': 'xxxxxxxxx', 'name2': 'yyyyyyyyy', 'name3': 'zzzzzzzzz'}