2.1 - Bag and XML
2.1.1 - toXml
A bag can be exported to an xml source with the method toXml() This method returns a text, that is a complete standard XML version of the Bag, including the encoding tag <?xml version=\'1.0\' encoding=\'UTF-8\'?>. Since an XML document needs an unique root node, the method creates as outer level the node <GenRoBag?>. Each bag becomes an XML block that contains other XML elements.
| Bag's item | XML element |
| label | tag |
| value | element's content |
| attributes | attributes |
toXml() may receive twe optional parameters:
- filename, that is the path of the output file. If filename is passed, the method returns None, and creates the file at the correct position.
- encoding is used to set the XML encoding: default value is UTF-8.
XML is a very common instrument to transport data, but transforming any datastructure into XML doument makes you loss the data types. This does't happen with the method toXml(). The method adds for each XML element a special attribute called '_T' that represents a code of the original type of item's value, unless the original type was string.
mybag= Bag() mybag['birthday']=datetime.date(1974,11,23) mybag['height']=1.76 mybag['weight']=65 xml_source=mybag.toXml() >>> print xml_source <?xml version='1.0' encoding='UTF-8'?> <GenRoBag> <birthday _T="D">1974-11-23</birthday> <height _T="R">1.76</height> <weight _T="L">65</weight> </GenRoBag>
Here is a table that show the keywords used to represents data types.
| Codes | Data Type |
| 'T' | txt |
| 'R' | float |
| 'L' | int |
| 'B | bool |
| 'D' | datetime |
| 'DT' | datetime |
| 'H' | datetime.time |
Also attributes' types aren't lost during the transformation, in fact in the value of each attribute is added a substring composed by '::type', unless it's original type was string.
mybag.setAttr('height',lastMeasure=datetime.date(2006,10,3))
xml_source = mybag.toXml()
>>> print xml_source
<?xml version='1.0' encoding='UTF-8'?>
<GenRoBag>
<birthday _T="D">1974-11-23</birthday>
<height _T="R" lastMeasure="2006-10-03::D">1.76</height>
<weight _T="L">65</weight>
</GenRoBag>
2.1.2 - from XML
If the Bag's constuctor receives as parameter source a filepath, an URL or a string that contains XML source, it creates a Bag that represents the XML document. If the XML source provides type indication, such as _T attribute or ::Type suffix, bag's values and attributes will have the correct type.
xmlbag=Bag(xml_source) >>> print xmlbag 0 - (date) birthday: 1974-11-23 1 - (float) height: 1.76 <lastMeasure='2006-10-03::D'> 2 - (int) weight: 65
