~camptocamp/c2c-rd-addons/7.0

120.1.3 by Gerhard Könighofer
table_generate_csv, xml_template added
1
# -*- coding: utf-8 -*-
2
##############################################
3
#
4
# Swing Entwicklung betrieblicher Informationssysteme GmbH
5
# (<http://www.swing-system.com>)
943 by ferdinand
[FIX] unify author name
6
# Copyright (C) ChriCar Beteiligungs- und Beratungs- GmbH
120.1.3 by Gerhard Könighofer
table_generate_csv, xml_template added
7
# all rights reserved
8
#    24-JUN-2009 (GK) created
9
#    02-AUG-2009 (GK) Interface changed from file to string
10
#
11
# WARNING: This program as such is intended to be used by professional
12
# programmers who take the whole responsability of assessing all potential
13
# consequences resulting from its eventual inadequacies and bugs.
14
# End users who are looking for a ready-to-use solution with commercial
15
# garantees and support are strongly adviced to contract a Free Software
16
# Service Company.
17
#
18
# This program is Free Software; you can redistribute it and/or
19
# modify it under the terms of the GNU General Public License
20
# as published by the Free Software Foundation; either version 3
21
# of the License, or (at your option) any later version.
22
#
23
# This program is distributed in the hope that it will be useful,
24
# but WITHOUT ANY WARRANTY; without even the implied warranty of
25
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26
# GNU General Public License for more details.
27
#
28
# You should have received a copy of the GNU General Public License
29
# along with this program; if not, see <http://www.gnu.org/licenses/> or
30
# write to the Free Software Foundation, Inc.,
31
# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
32
#
33
###############################################
34
from lxml import etree
167.44.37 by Gerhard Könighofer
improved logging, improved import structure
35
import logging
120.1.3 by Gerhard Könighofer
table_generate_csv, xml_template added
36
37
class XML_Generator (object) :
167.44.37 by Gerhard Könighofer
improved logging, improved import structure
38
    _logger = logging.getLogger('XML_Generator')
120.1.3 by Gerhard Könighofer
table_generate_csv, xml_template added
39
40
    def __init__ (self, template, nsmap=None) :
41
        self.root  = etree.fromstring (template)
42
        self.nsmap = nsmap
43
    # end def __init__
44
    
45
    def generate (self, **scope_dict) : 
46
        if self.nsmap :
47
            root = etree.Element (self.root.tag, self.root.attrib, nsmap = self.nsmap)
48
        else :
49
            root = etree.Element (self.root.tag, self.root.attrib)
50
        self.out = etree.ElementTree (root)
51
        self._iterate (self.root, root, scope_dict)
52
        return self.out
53
    # end def generate
54
    
55
    def write (self, xml_file, pretty = True) :
56
        from xml.dom.ext import PrettyPrint
57
        from xml.dom.ext.reader.Sax import FromXmlFile
58
59
        try :
60
            f = open (xml_file, "w")
61
            try :
62
                self.out.write (f)
63
            finally :
64
                f.close ()
65
        except (SystemExit, KeyboardInterrupt), exc :
66
            raise
67
        
68
        if pretty :
69
            doc = FromXmlFile (xml_file)
70
            try :
71
                f = open (xml_file, "w")
72
                try :
73
                    PrettyPrint (doc, f)
74
                finally :
75
                    f.close ()
76
            except (SystemExit, KeyboardInterrupt), exc :
77
                raise
78
    # end def write
79
80
    def _iterate (self, elm, out, scope_dict) :
81
        for name,value in out.items () :
82
            if name [0:9] == "attr-name" :
83
                del out.attrib[name]
84
                del out.attrib["attr-eval" + name [9:]]
85
        for name, value in elm.items () :
86
            if name [0:9] == "attr-name" :
87
                nr = name [9:]
88
                try :
89
                    val = eval (elm.attrib ["attr-eval" + nr], scope_dict)
90
                    out.set (elm.attrib [name], unicode (val))
91
                except :
835.2.159 by Gerhard Könighofer
xml_template: error handling enhanced
92
                    self._logger.error('ERROR in attr-eval for `%s` `%s` `%s`', elm.tag, name, elm.attrib["attr-eval" + nr])
120.1.3 by Gerhard Könighofer
table_generate_csv, xml_template added
93
                    raise 
94
            elif name [0:9] == "attr-eval" : pass
95
            elif name == "text-eval":
96
                try :
97
                    out.text = unicode (eval (value, scope_dict))
98
                except : 
835.2.159 by Gerhard Könighofer
xml_template: error handling enhanced
99
                    self._logger.error('ERROR in text-eval for `%s` `%s` `%s`', out.tag, name, value)
120.1.3 by Gerhard Könighofer
table_generate_csv, xml_template added
100
                    raise
101
        for c in elm.getchildren () :
102
            if "loop-eval" in c.attrib :
103
                try :
104
                    objs = eval \
105
                        ("[(%s) for %s in (%s)]" % 
106
                            ( c.attrib["var"]
107
                            , c.attrib["var"]
108
                            , c.attrib["loop-eval"]
109
                            )
110
                        , scope_dict 
111
                        )
112
                except :
835.2.159 by Gerhard Könighofer
xml_template: error handling enhanced
113
                    self._logger.error('ERROR in loop-eval for `%s` `%s`', c.tag, c.attrib["loop-eval"])
120.1.3 by Gerhard Könighofer
table_generate_csv, xml_template added
114
                    raise
115
                if not ("omit_on_empty" in c.attrib and c.attrib["omit_on_empty"] == "True" and not objs) :
116
                    x = etree.SubElement (out, c.tag)
117
                    for o in objs :
118
                        scope_dict [c.attrib["var"]] = o
119
                        self._iterate (c, x, scope_dict)
120
                        del scope_dict [c.attrib ["var"]]
121
            elif "seq-eval" in c.attrib :
122
                try :
123
                    objs = eval \
124
                        ("[(%s) for %s in (%s)]" % 
125
                            ( c.attrib["var"]
126
                            , c.attrib["var"]
127
                            , c.attrib["seq-eval"]
128
                            )
129
                        , scope_dict 
130
                        )
131
                except :
835.2.159 by Gerhard Könighofer
xml_template: error handling enhanced
132
                    self._logger.error('ERROR in seq-eval for `%s` `%s`', c.tag, c.attrib["seq-eval"])
120.1.3 by Gerhard Könighofer
table_generate_csv, xml_template added
133
                    raise 
134
                for o in objs :
135
                    scope_dict [c.attrib["var"]] = o
136
                    x = etree.SubElement (out, c.tag)
137
                    self._iterate (c, x, scope_dict)
138
                    del scope_dict [c.attrib ["var"]]
139
            else :
140
                x = etree.SubElement (out, c.tag)
141
                for name, value in c.items () :
142
                    if name == "loop-eval" : pass
143
                    elif name == "seq-eval": pass
144
                    elif name == "var" : pass
145
                    elif name [0:9] == "attr-eval" : pass
146
                    elif name == "text-eval":
147
                        try :
148
                            x.text = unicode (eval (value, scope_dict))
149
                        except : 
835.2.159 by Gerhard Könighofer
xml_template: error handling enhanced
150
                            self._logger.error('ERROR in text-eval for `%s` `%s` `%s`', c.tag, name, value)
120.1.3 by Gerhard Könighofer
table_generate_csv, xml_template added
151
                            raise
152
                    elif name [0:9] == "attr-name" :
153
                        nr = name [9:]
154
                        try :
155
                            val = eval (c.attrib ["attr-eval" + nr], scope_dict)
156
                            x.set (c.attrib [name], unicode (val))
157
                        except :
835.2.159 by Gerhard Könighofer
xml_template: error handling enhanced
158
                            self._logger.error('ERROR in attr-eval for `%s` `%s` `%s`', c.tag, name, c.attrib["attr-eval" + nr])
120.1.3 by Gerhard Könighofer
table_generate_csv, xml_template added
159
                            raise
160
                    else :
161
                        x.set (name, value)
162
                self._iterate (c, x, scope_dict)
163
    # end def _iterate
164
# end class XML_Generator