[XML-SIG] RE: converting integer to string
Andrew M. Kuchling
akuchlin@cnri.reston.va.us
Wed, 7 Oct 1998 10:47:19 -0400 (EDT)
Tim Peters quoted:
>> Is there a function in Python to convert an integer value to
>> a string?
Here's an XML-based variant; the integer is marshalled into a simple
format, and the resulting XML file is then parsed into a Document
Object Model Tree. Obtaining the string value is then simply a matter
of retrieving the single 'integer' element in the tree, and getting
the value of its first child, which must be a Text node.
A useful property of this implementation is that it will return the
string value of the first integer in a tuple or list. Actually,
given a recursive data structure, it should return the string value of
the first integer found in a preorder traversal of the list.
So, for example:
print `xml_int2str( 5 )`
print `xml_int2str( (6,5) )`
print `xml_int2str( ("stupid string", 7,5) )`
outputs
'5'
'6'
'7'
def xml_int2str(n):
# Marshal the integer, sticking the result in a StringIO object.
import StringIO
mem_file = StringIO.StringIO()
from xml import marshal
data = marshal.dump( n, mem_file )
mem_file.seek(0)
# mem_file now contains something like:
# <?xml version="1.0"?>
# <!DOCTYPE marshal SYSTEM "marshal.dtd">
# <marshal><integer>5</integer></marshal>
# Parse this and convert it to a DOM tree.
from xml.sax import saxexts
from xml.dom.sax_builder import SaxBuilder
p = saxexts.make_parser()
dh = SaxBuilder()
p.setDocumentHandler(dh)
p.parseFile( mem_file )
# Get the root Document node.
doc = dh.document
# List all the 'integer' elements in the tree, and retrieve the
# value of the child of the first one, which should be a Text node
# containing the string '5'.
integer_list = doc.getElementsByTagName( 'integer' )
integer_elem = integer_list[0]
children = integer_elem.get_childNodes()
return children[0].get_nodeValue()
--
A.M. Kuchling http://starship.skyport.net/crew/amk/
REMIND ME AGAIN, he said, HOW THE LITTLE HORSE-SHAPED ONES MOVE.
-- Death on symbolic last games, in Terry Pratchett's _Small Gods_