473,581 Members | 2,638 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.SocketSett ingsObj.IPAddre ss

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(TestSetti ngsStore.Config FileName)
#ConfigDom
TSSElList =
ConfigDom.getEl ementsByTagName ("TargetSocketS ettings")
NumTargSocks = len(TSSElList)
if NumTargSocks > 0:
TargetIPAddrLis t =
TSSElList[0].getElementsByT agName("TargetI PAddr")
TargetIPPortLis t =
TSSElList[0].getElementsByT agName("TargetI PPort")
AddrListLen = len(TargetIPAdd rList)
PortListLen = len(TargetIPPor tList)
if AddrListLen > 0 and PortListLen > 0:
if TargetIPAddrLis t[0] <> "" and TargetIPPortLis t[0] <>
0:
StillNeedSettin gs = False

TestSettingsSto re.SettingsDict ionary['TargetIPAddr'] =
TargetIPAddrLis t[0]

TestSettingsSto re.SettingsDict ionary['TargetIPPort'] =
TargetIPPortLis t[0]

This I saved as Unicode from Notepad with encoding UTF-16:
<?xml version="1.0" encoding="UTF-16" ?>
<TargetSocketSe ttings>
<TargetIPAddr>1 27.0.0.1</TargetIPAddr>
<TargetIPPort>4 3210</TargetIPPort>
</TargetSocketSet tings>

this I saved as UTF-8 from Notepad with encoding UTF-8:
<?xml version="1.0" encoding="UTF-16" ?>
<TargetSocketSe ttings>
<TargetIPAddr>1 27.0.0.1</TargetIPAddr>
<TargetIPPort>4 3210</TargetIPPort>
</TargetSocketSet tings>

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 3457
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.SocketSett ingsObj.IPAddre ss

I get this error: [...] if TargetIPAddrLis t[0] <> "" and TargetIPPortLis t[0] <>
0:
StillNeedSettin gs = False

TestSettingsSto re.SettingsDict ionary['TargetIPAddr'] =
TargetIPAddrLis t[0]

TestSettingsSto re.SettingsDict ionary['TargetIPPort'] =
TargetIPPortLis t[0]

TargetIPAddrLis t[0] and TargetIPPortLis t[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 = TargetIPAddrLis t[0].firstChild.nod eValue
try:
port = int(TargetIPPor tList[0].firstChild.nod eValue)
except ValueError: # safely handle invalid strings for int
port = 0
if addr and port:
StillNeedSettin gs = False
TestSettingsSto re.SettingsDict ionary['TargetIPAddr'] = addr
TestSettingsSto re.SettingsDict ionary['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(TestSe ttingsStore.Con figFileName)
# ConfigTree represents the TargetSocketSet tings root element

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

if TargetIPAddr and TargetIPPort:
StillNeedSettin gs = False
TestSettingsSto re.SettingsDict ionary["TargetIPAd dr"] = TargetIPAddr
TestSettingsSto re.SettingsDict ionary["TargetIPPo rt"] = TargetIPPort

where ET is set by something like:

try:
import xml.etree.Eleme ntTree as ET # Python 2.5
except ImportError:
# http://effbot.org/zone/element-index.htm
import elementtree.Ele mentTree 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.Ele mentTree 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(setti ngs, elem, keys):
d = {}
for key in keys:
value = elem.findtext(k ey)
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(
TestSettingsSto re.SettingsDict ionary,
ConfigTree,
("TargetIPAddr" , "TargetIPPortX" )):
StillNeedSettin gs = False

</F>

Mar 22 '06 #3

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

Similar topics

1
11197
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 = FileContents.replace('Repl_learner',unicode(Request("learner"),'utf-8','igno re')) TypeError: coercing to Unicode: need string or buffer, instance...
0
1490
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 Tkinter callback Traceback (most recent call last):
6
2202
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
2462
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" Please Help, Pranav
5
18637
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 identifier (64 bytes corresponding to Unicode character string padded with '0' Unicode characters. CHAR File format version (32 bytes corresponding...
5
20007
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 Here's my script: results = context.module_retriever().tuples() # call to ZSQLMethod converted =
8
9914
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 INTO mean (mean_id,mean_eng_txt) VALUES (:id,:mean)""",id=id,mean=mean) I not surprisingly get this error message:
2
13977
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
2818
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 needs to be appended to is dbf file type, I wrote a dbf writer so adding data on the fly is not a problem, the problem is trying to get the correct...
0
7873
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7800
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8153
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7902
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5679
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5365
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3806
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1405
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1141
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.