0

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>
1
  • 4
    What have you tried so far? ElementTree and lxml are well-suited for the task. Commented May 22, 2018 at 5:48

2 Answers 2

2

I think this is better.

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.