3

What is the easiest way to navigate through XML with python?

<html>
 <body>
  <soapenv:envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:body>
    <getservicebyidresponse xmlns="http://www.something.com/soa/2.0/SRIManagement">
     <code xmlns="">
      0
     </code>
     <client xmlns="">
      <action xsi:nil="true">
      </action>
      <actionmode xsi:nil="true">
      </actionmode>
      <clientid>
       405965216
      </clientid>
      <firstname xsi:nil="true">
      </firstname>
      <id xsi:nil="true">
      </id>
      <lastname>
       Last Name
      </lastname>
      <role xsi:nil="true">
      </role>
      <state xsi:nil="true">
      </state>
     </client>
    </getservicebyidresponse>
   </soapenv:body>
  </soapenv:envelope>
 </body>
</html>

I would go with regex and try to get the values of the lines I need but is there a pythonic way? something like xml[0][1] etc?

3

1 Answer 1

6

As @deceze already pointed out, you can use xml.etree.ElementTree here.

import xml.etree.ElementTree as ET
tree = ET.parse("path_to_xml_file")
root = tree.getroot()

You can iterate over all children nodes of root:

for child in root.iter():
    if child.tag == 'clientid':
        print(child.tag, child.text.strip())

Children are nested, and we can access specific child nodes by index, so root[0][1] should work (as long as the indices are correct).

Sign up to request clarification or add additional context in comments.

8 Comments

This gives me IOError: [Errno 36] File name too long:
Kindly refer to this answer - stackoverflow.com/a/29891397/2689986. You are likely passing file contents instead of passing filename to the ET.parse function.
Ok so root = ET.fromstring(xml) fixes this, I dont have an XML File
for child in root: print(child.tag, child.attrib) gives me ('body', {})
for RHEL stock config (Python 2.6.6) its: root.getiterator(): now it works, and I understood what I need to do thank you
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.