0

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
{}
{}
{}
{}
{}
{}
{}
{}
3
  • 2
    node.attrib gives you a dictionary of the node's attributes. You want the node#s textual contents. Try print(name.text) instead. Commented Jul 17, 2018 at 9:37
  • @schwobaseggl That works! Appreciate the quick response.. Commented Jul 17, 2018 at 10:07
  • Your XML doesn't have any attributes. It consists entirely of elements and text nodes. There's nothing unusual in that. But you'll confuse everyone (and probably yourself) if you call them attributes when they aren't. Commented Jul 17, 2018 at 13:58

1 Answer 1

1

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

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.