Python BeautifulSoup XML Parsing

I'd recommend using the builtin ElementTree module. BeautifulSoup is meant to handle unwell-formed code like hacked up HTML, whereas XML is well-formed and meant to be read by an XML library.

Update: some of my recent reading here suggests lxml as a library built on and enhancing the standard ElementTree.


BeautifulSoup makes getting at attributes and values in xml really simple. I tweaked your example function to use these features.

import sys
from BeautifulSoup import BeautifulSoup as Soup

def parseLog(file):
    file = sys.argv[1]
    handler = open(file).read()
    soup = Soup(handler)
    for message in soup.findAll('message'):
        msg_attrs = dict(message.attrs)
        f_user = message.find('from').user
        f_user_dict = dict(f_user.attrs)
        print "%s: %s [%s @ %s]" % (f_user_dict[u'friendlyname'],
                                    message.find('text').decodeContents(),
                                    msg_attrs[u'date'],
                                    msg_attrs[u'time'])


if __name__ == "__main__":
    parseLog(sys.argv[1])