TypeError coercing to Unicode with field read from XML file

Ben Cartwright bencvt at gmail.com
Tue Mar 21 21:17:34 EST 2006


Randall Parker wrote:
> My problem is that once I parse the file with minidom and a field from
> it to another variable as shown with this line:
>             IPAddr = self.SocketSettingsObj.IPAddress
>
> I get this error:
[...]
>                 if TargetIPAddrList[0] <> "" and TargetIPPortList[0] <>
> 0:
>                     StillNeedSettings = False
>
> TestSettingsStore.SettingsDictionary['TargetIPAddr'] =
> TargetIPAddrList[0]
>
> TestSettingsStore.SettingsDictionary['TargetIPPort'] =
> TargetIPPortList[0]


TargetIPAddrList[0] and TargetIPPortList[0] are *not* a string and an
int, respectively.  They're both DOM elements.  If you want an int, you
have to explicitly cast the variable as an int.  Type matters in
Python:

  >>> '0' == 0
  False

Back to your code:  try a couple debugging print statements to see
exactly what your variables are.  The built-in type() function should
help.

To fix the problem, you need to dig a little deeper in the DOM, e.g.:

    addr = TargetIPAddrList[0].firstChild.nodeValue
    try:
        port = int(TargetIPPortList[0].firstChild.nodeValue)
    except ValueError:  # safely handle invalid strings for int
        port = 0
    if addr and port:
        StillNeedSettings = False
        TestSettingsStore.SettingsDictionary['TargetIPAddr'] = addr
        TestSettingsStore.SettingsDictionary['TargetIPPort'] = port

--Ben




More information about the Python-list mailing list