def toElement(project):

    def SIV(element, key, value):        
        " Set If Valid -- only set element attribute if value is not None. "
        if value is not None:
            #print " KEY: %s => %s" % (key, str(value))
            element.set(key, unicode(value))


    eProject = Element("Project")
    eProject.attrib['version'] = FILEFORMAT  

    eData = SubElement(eProject, "Datasets")
    for ds in project.datasets:
        
        if ds._array is None:
            logger.error("Empty Dataset: %s. NOT SAVED." % ds.key)
            continue

        # Table
        if isinstance(ds, Table):
            tbl = ds
            eTable = SubElement(eData, 'Table')

            # All information about the columns is stored in the
            # element tree.  Only the actual data will later on be
            # written to the archive.
            for n in range(tbl.ncols):
                eColumn = SubElement(eTable, 'Column')
                SIV(eColumn, 'name', tbl.get_name(n))
                dt = tbl.get_column_dtype(n)
                SIV(eColumn, 'format', '%s%s' % (dt.kind, str(dt.itemsize)))
                info = tbl.get_info(n)
                for k,v in info._values.iteritems():
                    if v is not None:
                        eAttribute = SubElement(eColumn, 'Attribute')
                        SIV(eAttribute, 'key', k)
                        eAttribute.text = v

            # general information (should be there for any other kind of
            # Dataset as well)
            SIV(eTable, 'key', ds.key)
            SIV(eTable, 'fileformat', 'CSV' )

            # write node information
            node_items = tbl.node_info._checks.keys()
            node_items.remove('metadata')
            iohelper.write_dict(eTable, 'NodeInfo', values_as_dict(tbl.node_info, node_items))
            iohelper.write_dict(eTable, 'NodeInfo', tbl.node_info.metadata)
        else:
            logger.error("Cannot save Dataset %s of type %s" % (ds.key, ds.__class__.__name__))
                                   
    ePlots = SubElement(eProject, "Plots")
    for plot in project.plots:
        ePlot = SubElement(ePlots, plot.__class__.__name__)
        SIV(ePlot, 'key', plot.key)
        SIV(ePlot, 'title', plot.get('title'))

        comment = plot.get('comment')
        if comment is not None:
            eComment = SubElement(ePlot, "comment")
            eComment.text = comment

        eLayers = SubElement(ePlot, "Layers")
        for layer in plot.layers:
            
            eLayer = SubElement(eLayers, "Layer")
            attrs = values_as_dict(layer, ['type', 'grid', 'title', 'visible'], default=None)            
            iohelper.set_attributes(eLayer, attrs)

#             # group properties
#             eGroups = SubElement(eLayer, "Groups")

#             def groups_to_element(eGroups, keys):
#                 for key in keys:
#                     print "Writing group property ", key                
#                     group = layer.get_value(key)
#                     if group is not None:
#                         groupname = group.__class__.__name__
#                         eGroup = SubElement(eGroups, groupname)
#                         # TODO: cycle_list is missing, because it is a list!
#                         attrs = group.get_values(include=['type','value', 'range_start', 'range_stop', 'range_step'],
#                                      default=None)
#                         iohelper.set_attributes(eGroup, attrs)
                        
#             groups_to_element(eGroups, ['group_linestyle',
#                                         'group_linemarker',
#                                         'group_linewidth',
#                                         'group_linecolor'])
                
            # axes
            for (key, axis) in layer.axes.iteritems():
                eAxis = SubElement(eLayer, "Axis")
                attrs = values_as_dict(axis,['label', 'scale', 'start', 'end', 'format'],default=None)
                attrs['key'] = key
                iohelper.set_attributes(eAxis, attrs)

            # legend
            legend = layer.legend
            if legend is not None:
                eLegend = SubElement(eLayer, "Legend")
                attrs = values_as_dict(legend, ['label','position','visible','border','x','y'],default=None)
                iohelper.set_attributes(eLegend, attrs)

            # lines
            for line in layer.lines:
                eLine = SubElement(eLayer, "Line")

                # For the line source we must check first
                # if this is not a temporary source.
                # TODO: if it was a temporary source we either
                # need to ignore the source (current situation)
                # or add the temporary dataset to the project.
                if line.source is not None:
                    if project.has_dataset(key=line.source.key):
                        SIV(eLine, 'source', line.source.key)
                    else:
                        logger.warn("Invalid line source. Skipped source.")
                
                attrs = values_as_dict(line, ['width','label','style','marker','visible', 'color','marker_color', 'marker_size', 'cx','cy','row_first','row_last','cxerr','cyerr'],default=None)
                iohelper.set_attributes(eLine, attrs)

            # layer.labels
            if len(layer.labels) > 0:
                eLabels = SubElement(eLayer, "Labels")
                for label in layer.labels:
                    eLabel = SubElement(eLabels, "Label")
                    attrs = values_as_dict(label, ['x','y','system','valign','halign'],default=None)
                    iohelper.set_attributes(eLabel, attrs)
                    eLabel.text = label.get('text')

    iohelper.beautify_element(eProject)
        
    return eProject
def toElement(project):

    def SIV(element, key, value):        
        " Set If Valid -- only set element attribute if value is not None. "
        if value is not None:
            #print " KEY: %s => %s" % (key, str(value))
            element.set(key, unicode(value))


    eProject = Element("Project")
    eProject.attrib['version'] = FILEFORMAT

    eDatasets = SubElement(eProject, "Datasets")
    for ds in project.datasets:
        if ds.get_data() is None:
            raise RuntimeError("EMPTY DATASET '%s'" % ds.key)
        
        if isinstance(ds.data, Table):
            tbl = ds.data
            
            eData = SubElement(eDatasets, 'Table')            
            SIV(eData, 'ncols', tbl.ncols)
            SIV(eData, 'typecodes', tbl.typecodes_as_string)

            # We write all Column properties except for the
            # key and the data to the element tree, so we don't
            # need to put that information into the data file.
            n = 0
            for column in tbl.get_columns():
                kw = column.get_values(exclude=['key','data'])
                if len(kw) > 0:
                    eColumn = SubElement(eData, 'Column')
                    SIV(eColumn, 'n', n)
                    for k,v in kw.iteritems():
                        if v is not None:
                            eInfo = SubElement(eColumn, 'Info')
                            SIV(eInfo, 'key', k)
                            eInfo.text = v
                n += 1
                
            
        elif isinstance(ds.data, ArrayType): # TODO: untested
            eData = SubElement(eDatasets, 'Array')
        else:
            raise RuntimeError("Invalid dataset", ds)
        
        SIV(eData, 'key', ds.rget('key'))
        SIV(eData, 'fileformat', 'CSV' )

        # TODO: iohelper.write_dict, but then I need a transformation
        # TODO: of the file format: Metaitem -> Item
        if len(ds.metadata) > 0:
            eMetadata = SubElement(eData, "Metadata")
            for k,v in ds.metadata.iteritems():
                eMetaitem = SubElement(eMetadata, 'Metaitem')
                eMetaitem.set('key', k)
                eMetaitem.text = str(v)
                       
    ePlots = SubElement(eProject, "Plots")
    for plot in project.plots:
        ePlot = SubElement(ePlots, plot.__class__.__name__)
        SIV(ePlot, 'key', plot.rget('key'))
        SIV(ePlot, 'title', plot.rget('title'))

        comment = plot.rget('comment')
        if comment is not None:
            eComment = SubElement(ePlot, "comment")
            eComment.text = comment

        eLayers = SubElement(ePlot, "Layers")
        for layer in plot.layers:
            
            eLayer = SubElement(eLayers, "Layer")
            attrs = layer.get_values(['type', 'grid', 'title', 'visible'], default=None)            
            iohelper.set_attributes(eLayer, attrs)
                            
            for (key, axis) in layer.axes.iteritems():
                eAxis = SubElement(eLayer, "Axis")
                attrs = axis.get_values(['label', 'scale', 'start', 'end', 'format'],default=None)
                attrs['key'] = key
                iohelper.set_attributes(eAxis, attrs)

            legend = layer.legend
            if legend is not None:
                eLegend = SubElement(eLayer, "Legend")
                attrs = legend.get_values(['label','position','visible','border','x','y'],default=None)
                iohelper.set_attributes(eLegend, attrs)
                                     
            for line in layer.lines:
                eLine = SubElement(eLayer, "Line")

                # For the line source we must check first
                # if this is not a temporary source.
                # TODO: if it was a temporary source we either
                # need to ignore the source (current situation)
                # or add the temporary dataset to the project.
                if line.source is not None:
                    if project.has_dataset(key=line.source.key):
                        SIV(eLine, 'source', line.source.rget('key'))
                    else:
                        logger.warn("Invalid line source. Skipped source.")
                
                SIV(eLine, 'width', line.rget('width'))

                attrs = line.get_values(['width','label','style','marker','visible', 'cx','cy','row_first','row_last','cxerr','cyerr'],default=None)
                iohelper.set_attributes(eLine, attrs)

            # layer.labels
            if len(layer.labels) > 0:
                eLabels = SubElement(eLayer, "Labels")
                for label in layer.labels:
                    eLabel = SubElement(eLabels, "Label")
                    attrs = label.get_values(['x','y','system','valign','halign'],default=None)
                    iohelper.set_attributes(eLabel, attrs)
                    eLabel.text = label.rget('text')

    iohelper.beautify_element(eProject)
        
    return eProject