Atul
Atul

Reputation: 130

Get value for XML attribute in python

I am trying to parse an XML file in python and seems like my XML is different from the normal nomenclature.

Below is my XML snippet:

   <records>
            <record>
                <parameter>
                    <name>Server</name>
                    <value>Application_server_01</value>
                </parameter
            </record>
   </records>

I am trying to get the value of "parameter" name and value however i seem to get empty value.

I checked the online documentation and almost all XML seems to be in the below format

<neighbor name="Switzerland" direction="W"/>

I am able to parse this fine, how can i get the values for my XML attributes without changing the formatting.

working code

import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
for neighbor in root.iter('neighbor'):
    print(neighbor.attrib)

output

C:/Users/xxxxxx/PycharmProjects/default/parse.py
{'direction': 'E', 'name': 'Austria'}
{'direction': 'W', 'name': 'Switzerland'}
{'direction': 'N', 'name': 'Malaysia'}
{'direction': 'W', 'name': 'Costa Rica'}
{'direction': 'E', 'name': 'Colombia'}

PS: I will be using the XML to fire an API call and doubt if the downstream application would like the second way of formatting.

Below is my python code

import xml.etree.ElementTree as ET
tree = ET.parse('at.xml')
root = tree.getroot()
for name in root.iter('name'):
    print(name.attrib)

Output for the above code

C:/Users/xxxxxx/PycharmProjects/default/learning.py
{}
{}
{}
{}
{}
{}
{}
{}

Upvotes: 0

Views: 1958

Answers (1)

user9455968
user9455968

Reputation:

Use lxml and XPath:

from lxml import etree as et

tree = et.parse(open("/tmp/so.xml"))
name = tree.xpath("/records/record/parameter/name/text()")[0]   
value = tree.xpath("/records/record/parameter/value/text()")[0]
print(name, value)

Output:

Server Application_server_01

Upvotes: 1

Related Questions