XML parsing with python

Consider the following xml file:

<?xml version="1.0"?>
 <config version="6.1.0" urldb="paloaltonetworks">
      <entry name="admin">

Root of the above xml file is “config“. Root have attribute as “version, urldb”.
Here in <mgt-config></mgt-config> mgt-config is element.

Following is the script to parse the above xml file:

import xml.etree.ElementTree as ET
tree = ET.parse(f)

#get the root of the xml file and put is in variable 'root' 

print 'root is ' +root.tag
# print the root of the xml file. "tag" can be used to print the element as well. 

print  root.attrib.values()
# print all the attribute value.

print root.attrib 
for child in root.findall('./mgt-config/users/entry'):
# find all element named as entry inside users.  
    print child.tag + ' child tag' 
        # print all the element.
        for all in child.findall('./'):
        # This for loop will print all element inside entry.
                print all.tag
                if all.tag=='phash':

Output of the script is as follows:

root is config
['paloaltonetworks', '6.1.0']
{'urldb': 'paloaltonetworks', 'version': '6.1.0'}
entry child tag
This entry was posted in Python and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s