473,320 Members | 2,111 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

TypeError coercing to Unicode with field read from XML file

Running Python 2.4.2 on Windows in SPE. I have a very small XML file
(see below) that is in UTF-8 and saved by Windows Notepad as such. I'm
reading it with minidom.

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:

File "<string>", line 1, in connect
TypeError: coercing to Unicode: need string or buffer, instance found

This is the section of code that reads the XML file:

ConfigDom = parse(TestSettingsStore.ConfigFileName)
#ConfigDom
TSSElList =
ConfigDom.getElementsByTagName("TargetSocketSettin gs")
NumTargSocks = len(TSSElList)
if NumTargSocks > 0:
TargetIPAddrList =
TSSElList[0].getElementsByTagName("TargetIPAddr")
TargetIPPortList =
TSSElList[0].getElementsByTagName("TargetIPPort")
AddrListLen = len(TargetIPAddrList)
PortListLen = len(TargetIPPortList)
if AddrListLen > 0 and PortListLen > 0:
if TargetIPAddrList[0] <> "" and TargetIPPortList[0] <>
0:
StillNeedSettings = False

TestSettingsStore.SettingsDictionary['TargetIPAddr'] =
TargetIPAddrList[0]

TestSettingsStore.SettingsDictionary['TargetIPPort'] =
TargetIPPortList[0]

This I saved as Unicode from Notepad with encoding UTF-16:
<?xml version="1.0" encoding="UTF-16" ?>
<TargetSocketSettings>
<TargetIPAddr>127.0.0.1</TargetIPAddr>
<TargetIPPort>43210</TargetIPPort>
</TargetSocketSettings>

this I saved as UTF-8 from Notepad with encoding UTF-8:
<?xml version="1.0" encoding="UTF-16" ?>
<TargetSocketSettings>
<TargetIPAddr>127.0.0.1</TargetIPAddr>
<TargetIPPort>43210</TargetIPPort>
</TargetSocketSettings>

Both formats create the same error.

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

Mar 22 '06 #1
2 3439
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

Mar 22 '06 #2
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:

try:
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
settings.update(d)
return True

if getconfig(
TestSettingsStore.SettingsDictionary,
ConfigTree,
("TargetIPAddr", "TargetIPPortX")):
StillNeedSettings = False

</F>

Mar 22 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Stuart Forsyth | last post by:
What can I do about this error, i am tearing my hair out! Python ActiveX Scripting Engine (0x80020009) Traceback (most recent call last): File "<Script Block >", line 58, in ? FileContents =...
0
by: Michael Spencer | last post by:
Using: Python 2.3.3 Tkinter.TclVersion = 8.4000000000000004 Windows XP Calling edit_modified() on a Tkinter.Text object raises TypeError when it gets a Boolean True response. Exception in...
6
by: Mike Brown | last post by:
This works as expected (this is on an ASCII terminal): >>> unicode('asdf\xff', errors='replace') u'asdf\ufffd' This does not work as I expect it to: >>> class C: .... def __str__(self):
2
by: Pranav Bagora | last post by:
Hello , i am trying to change mode of files using the os.chmod()function. But i am getting an error " os.chmod(outfile,0700) TypeError: coercing to Unicode: need string or buffer, file found"...
5
by: Jamie | last post by:
I have a file that was written using Java and the file has unicode strings. What is the best way to deal with these in C? The file definition reads: Data Field Description CHAR File...
5
by: Jon Bowlas | last post by:
Hi listers, I wrote this script in Zope some time ago and it worked for a while, but now I'm getting the following error: TypeError: coercing to Unicode: need string or buffer, NoneType found ...
8
by: Richard Schulman | last post by:
Sorry to be back at the goodly well so soon, but... ....when I execute the following -- variable mean_eng_txt being utf-16LE and its datatype nvarchar2(79) in Oracle: cursor.execute("""INSERT...
2
by: kath | last post by:
Hi, the following shows the contents of "datebook.xls" Date 8/9/2006 8/9/2006 8/9/2006 8/9/2006 8/9/2006
2
by: JimmyKoolPantz | last post by:
We purchased som software for encoding a barcode. We want to automate the process of converting a number to a readable barcode. However, I am having a few issues. The file that the barcode...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.