Parsing XML in Python: A Quick Working Sample

In my recent consulting projects, I used Python on various projects including the VMware pyVmomi () for managing vSphere. Because XML is ubiqutous these days, I had to use XML for configuration, passing information, etc. Parsing XML is a very basic part of using XML. The following sample code can achieve the same thing (print out may be different) as the C# sample that parses XML I wrote before.

Because the code uses the cElementTree that is backed up by native C implementation, it runs way faster and uses much less memory than its portable equivalent ElementTree. Both cElementTree and ElementTree share the same interfaces, you can just change the “cElementTree” to “ElementTree” in the import statement.

Lost VMs or Containers? Too Many Consoles? Too Slow GUI? Time to learn how to "Google" and manage your VMware and clouds in a fast and secure HTML5 App.

__author__ = 'Steve Jin'
from xml.etree import cElementTree as ET
class Book:
    id = None
    title = None
    author = None
    def __str__(self):
        return + ": " + self.title + " by " +
tree = ET.parse("books.xml")
catalog = tree.getroot()
for node in catalog:
    book = Book() = node.find('author').text
    book.title = node.find('title').text = node.attrib["id"]
    print book

The books.xml is exactly the same as the previous article.

<?xml version="1.0"?>
  <book id="bk101">
    <author>Steve Jin</author>
    <title>VMware VI and vSphere SDK</title>
      An in-depth introduction on VMware vSphere SDK and open source vijava API.
  <book id="bk102">
    <author>Steve Jin</author>
      An in-depth introduction on something.
This entry was posted in Software Development and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *


You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


    My company has created products like vSearch ("Super vCenter"), vijavaNG APIs, EAM APIs, ICE tool. We also help clients with virtualization and cloud computing on customized development, training. Should you, or someone you know, need these products and services, please feel free to contact me: steve __AT__

    Me: Steve Jin, VMware vExpert who authored the VMware VI and vSphere SDK by Prentice Hall, and created the de factor open source vSphere Java API while working at VMware engineering. Companies like Cisco, EMC, NetApp, HP, Dell, VMware, are among the users of the API and other tools I developed for their products, internal IT orchestration, and test automation.