Home > Software design >  Trying to parse xml line for specific values associated with a tag using element tree in python
Trying to parse xml line for specific values associated with a tag using element tree in python

Time:07-07

I am currently struggling trying to figure out how to parse out specific information from a specific tag that is in a xml file.

The xml file is structured as such

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <configSections>
        |
        |
   </configSections>
   <connectionStrings>
        <clear />
        <add name="Database1" connectionString="DataSource=[ServerName];Initial Catalog=[DatabaseName]; User ID=user2;Password=oogabooga1" providerName="Database1provider"/>
        <add name="Database12" connectionString="DataSource=[ServerName];Initial Catalog=[DatabaseName]; User ID=user1;Password=oogabooga2" providerName="Database2provider"/>

   </connectionStrings>

I am trying to parse out the name, UserId and Password from connectionStrings.

I am stuck on trying to get parse out the data using Element Tree, any ideas here?

import xml.etree.ElementTree as ET

webconfig = etree.parse(filepath)

from elem in webconfig.findall('configuration'):
    print(elem.text)

Any help is greatly appreciated

CodePudding user response:

Does this help?


import xml.etree.ElementTree as ET

someXML = '''<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <configSections>
        |
        |
   </configSections>
   <connectionStrings>
        <clear />
        <add name="Database1" connectionString="DataSource=[ServerName];Initial Catalog=[DatabaseName]; User ID=user2;Password=oogabooga1" providerName="Database1provider"/>
        <add name="Database12" connectionString="DataSource=[ServerName];Initial Catalog=[DatabaseName]; User ID=user1;Password=oogabooga2" providerName="Database2provider"/>
   </connectionStrings>
</configuration>
'''

data = ET.fromstring(someXML)

for i in data.findall('connectionStrings'):
    for item in i.findall('add'):
        print(item.attrib)

Please note there were several syntax issues in your XML which I cleaned up.

Also, if you need to get individual key value pairs, you can use this:


for i in data.findall('connectionStrings'):
    for item in i.findall('add'):
        print(item.get('name'))

  • Related