TypeError coercing to Unicode with field read from XML file

Fredrik Lundh fredrik at pythonware.com
Wed Mar 22 09:09:09 CET 2006

Randall Parker wrote:

> I'm probably doing something dumb as I've never done XML in Python
> before. Any ideas what?

using minidom ? ;-)

if you're not wedded to minidom, there are alternatives that are easier
to use for things like this.  here's an ElementTree version of your code:

    ConfigTree = ET.parse(TestSettingsStore.ConfigFileName)
    # ConfigTree represents the TargetSocketSettings root element

    TargetIPAddr = tree.findtext("TargetIPAddr")
    TargetIPPort = tree.findtext("TargetIPPort")

    if TargetIPAddr and TargetIPPort:
        StillNeedSettings = False
        TestSettingsStore.SettingsDictionary["TargetIPAddr"] = TargetIPAddr
        TestSettingsStore.SettingsDictionary["TargetIPPort"] = TargetIPPort

where ET is set by something like:

        import xml.etree.ElementTree as ET # Python 2.5
    except ImportError:
        # http://effbot.org/zone/element-index.htm
        import elementtree.ElementTree as ET

if you don't want to ship the entire ElementTree library with your app,
you can just add the ElementTree.py module somewhere, and do e.g.

    import myapp.utils.ElementTree as ET


if you plan to grab more stuff from XML files, you might wish to apply the
DRY principle (google it!), and use a little helper to copy the variables from
the XML file to your dictionary:

    def getconfig(settings, elem, keys):
        d = {}
        for key in keys:
            value = elem.findtext(key)
            if not value:
                return False
            d[key] = value
        # only update the settings dict if all keys were present
        return True

    if getconfig(
            ("TargetIPAddr", "TargetIPPortX")):
        StillNeedSettings = False


More information about the Python-list mailing list