Question

I have a very small XML file (22 lines) with 5 elements(?) and I only want one value out of it.

This is the only way I can get the value I have found without using regular expressions

from xml.dom.minidom import parse
float(parse(filePath).getElementsByTagName('InfoType')[0].getElementsByTagName('SpecificInfo')[0].firstChild.data)

I feel like I'm missing something. There has to be a more pythonic way to handle XML, right?

Was it helpful?

Solution

The ElementTree library is a lot more Pythonic than xml.dom.minidom. If I'm understanding your XML structure right, your code would look something like this using ElementTree:

import xml.etree.ElementTree as ET
tree = ET.parse(filePath)
data = float(tree.find('InfoType/SpecificInfo')[0].text)

That should be a lot cleaner than what you're currently doing.

OTHER TIPS

Instead of those long DOM browsing functions you can at least use pyQuery: http://pythonhosted.org/pyquery/ (jQuery syntax in Python)

Using elementtree is more Pythonic way of getting individual values from XML:

http://docs.python.org/2/library/xml.etree.elementtree.html

And it'e a part of standard library for recent Python versions.

I think it is a little premature to dismiss the minidom API for being unpythonic. With a couple of helper functions we can get as pythonic as we wish, eg:

# Helper function to wrap the DOM element/attribute creation API.
def El( tag, attribs = None, text = None ):
    el = doc.createElement( tag )
    if text: el.appendChild( doc.createTextNode( text ))
    if attribs is None: return el
    for k, v in attribs.iteritems(): el.setAttribute( k, v )
    return el

# Construct an element tree from the passed tree.
def make_els( parent_el, this_el, child_els ):
    parent_el.appendChild( this_el )
    for x in child_els:
        if type( x ) is tuple:
            child_el, grandchild_els = x
            make_els( this_el, child_el, grandchild_els )
        else:
            this_el.appendChild( x )

doc.removeChild( doc.documentElement )
make_els( doc, El( 'html', { 'xmlns': 'http://www.w3.org/1999/xhtml', 'dir': 'ltr', 'lang': 'en' }), [
    (   El( 'head' ), [
        El( 'meta', { 'http-equiv': 'Content-Type', 'content': 'text/html; charset=utf-8' }),
        El( 'meta', { 'http-equiv': 'Content-Style-Type', 'content': 'text/css' }),
        El( 'link', { 'rel': 'stylesheet', 'type': 'text/css', 'href': 'main.css', 'title': 'Default Stylesheet' }),
        El( 'title', {}, 'XXXX XXXX XXXXr {}, {}'.format( args.xxxx, env.build_time ))
    ]),
    (   El( 'frameset', { 'cols': '20%, 80%' }), [
        El( 'frame', { 'src': 'xxx_list.html', 'name': 'listframe', 'title': 'XXXX XXXX XXXX' }),
        El( 'frame', { 'src': 'xxx_all_xxxx_all.html', 'name': 'regframe', 'title': 'XXX XXXX XXXX' }),
        (   El( 'noframes' ), [
            (   El( 'body' ), [
                El( 'h2', {}, 'Frame Alert' ),
                El( 'p', {}, 'This document is designed to be viewed using the frames feature.' )
            ])
        ])
    ])
])
print '\ndoc:\n', doc.toprettyxml( indent = '  ' )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top