Converts a Jython variable into an XML string.
xmlstr = xml_format(v,attswitch='on',name='root')
xml_format converts Jython variables and data structures (including deeply nested data structures) into XML and returns the XML as string.
v Jython variable of type int, float, long, string, dictionary, list, tuple, complex
attswitch optional,
default='on':
'on' writes header attributes idx, size,
type for identification by Jython
when parsing the XML later;
'off' writes "plain" XML without header attributes.
name optional, give root element a specific name, e.g. 'project'.
xmlstr string, containing XML description of the variable v.
The root element of the created XML string is called 'root' by default but this can be overwritten with the name input parameter. A default xml_tb_version attribute of "X.Y-py" is added to the root element unless attswitch is set to 'off'. X and Y are Version numbers which identify the toolbox used.
If attswitch is set to 'on' (by default), the attributes idx, type, and size will be added to the XML element headers. This allows xml_parse to parse and convert the XML string correctly back into the original Jython variable or data structure.
If attswitch is set to 'off', some of the information is lost and subsequently the contents of XML elements will be read in as strings when converting back using xml_parse (see tutorial section).
This example shows how to convert a simple number into an XML string. Note that we could have used xml_format(5.0) instead.
from gdxml import *
v = 5.0
xmlstr = xml_format(v)
print xmlstr
<root
xml_tb_version="0.1-py" idx="1" type="double"
size="1 1">5</root>
We can tell the command to ignore all the attributes and obtain the following XML:
xmlstr = xml_format(v,'off')
print xmlstr
<root>5</root>
The root elements can be assigned a different name by adding this as third parameter to the xml_format function:
xmlstr = xml_format(v,'off','myXmlNumber')
print xmlstr
<myXmlNumber>5</myXmlNumber>
Strings can also be converted into XML:
v = 'The Hitchhikers Guide to the Galaxy'
xmlstr = xml_format(v)
print xmlstr
<root
xml_tb_version="0.1-py"
idx="1" type="char" size="1 35">
The Hitchhikers Guide to the Galaxy</root>
One of the most powerful ways to use the XML Toolbox is to convert whole deeply nested data structures into XML:
v = {'project' : {'name' : 'my Project no. 001'}}
v['project']['date'] = '2005-01-01'
v['project']['uid'] = '208d0174-a752-f391-faf2-45bc397'
v['comment'] = 'This is a new project'
xmlstr = xml_format(v,'off')
print xmlstr
<root>
<project>
<name>my Project no. 001</name>
<date>2004-09-09 16:18:29</date>
<uid>208d0174-a752-f391-faf2-45bc397</uid>
</project>
<comment>This is a new project</comment>
</root>
Copyright © 2005, The Geodise Project, University of Southampton