Welcome, guest | Sign In | My Account | Store | Cart

This is merely a sketch for a bare-bones XML 1.0 generator.I wrote it for working on little tasks for which other generators seem to be too much complex. Python version used to test this code was 2.4.3 on a Win32 platform.

Python, 237 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
__name__        = 'xmlfetch.py'
__author__      = 'Trionice'
__date__        = '9-11-2006'
__version__     = '0.1.1'
__license__     = 'GPL'
__copyright__   = 'Copyright (c) Ivan Furone, 2006'


__all__ = ['xmlfetch','operator','repr','types']
filter(__import__, __all__)



class XMLObj(object):

    tree = str()

    def __init__(self,tree=''):

        self.tree = tree + XMLObj.tree
        return self.tree

class XMLFetch(XMLObj):

     def __init__(self, version=1.0, charset="UTF-8", standalone="yes"):
         self.version =     version
         self.charset =     charset
         self.standalone =  standalone

         self.tree = XMLObj.__init__(self,tree=XMLObj.tree)
         self.nodes = ()

     def _gendecl(self):

        """
        Returns a string representing a standard XML 1.0 declaration equal
        as it is default initialized in __init__.

        """

        return '<? xml version="%f" charset="%s" standalone="%s"?>' \
    % (self.version,self.charset,self.standalone)

     def _embedparser(self, tree, XMLparser='xml.sax'):

         """
         Returns a correctly parsed chunk of valid xml according to the parsing
         libraries it relies on (currently it relies on xml.sax only)

         """

         from xml.sax.handler import ContentHandler
         if XMLparser == 'xml.sax':import xml.sax
         pstring = tree;TempHandler = ContentHandler()
         try:
            do_parse = xml.sax.parseString(pstring,TempHandler)
         except:
            return False
         return True

     def _is_node(self, node):

        """
        Checks if a given node is present in the class dict that holds the nodes for
        further processing.

        """

        is_node = node in self.__dict__[nodes]
        if is_node:
            flag = True
        return flag

     def _diffnode(self, node):

        """
        Find equivalence between two nodes.

        """

        if map (self._is_node,(nodeA, nodeB))[0] == True:
            diff = cmp(self, nodeA, nodeB)
            if diff == 0:
                return nodeA
            else: return None

     def yieldattr(self, attr):


        """
         Takes as argument a dictionary which keys are the names of a node's
         attributes,each one bound with their value.It processes the dict's items,
         returning a string from the resulting list of just-unpacked tuples.

        """
        t = attr.items()
        t2 = []
        for item in t[:]:
            t2.append(' %s = "%s" ' %(item[0],item[1]))
            if not item:
                break
                try :
                    return ''
                except :
                    pass
            else :
                continue
        return str(t2).lstrip("['").rstrip("']").replace("'","").replace(",","")

     def buildnode(self, nodename, splitargs, attrib={}, content=''):

        """
        Takes a node's name,attributes and content - a string,a mapping and another
        string respectively - and returns an XML node crafted accordingly with
        the parameters aforementioned.

        nodename is the node's name expressed as a string;splitargs is a boolean
        which when set to zero returns the node as a whole element,and when set to
        1 will return each one separately inspite.

        """
        
        node1 = '<' + nodename + self.yieldattr(attrib) + '>'
        node2 = '</' + nodename + '>'
        if splitargs == 0:
            node = node1 + content + node2
            return node
        else:
            return node1,content,node2

     def enclosenode(self, parent, node, pcontent='',ncontent='',\
      pattrib=None, nattrib=None):

        """
        Takes as arguments the name of a parent node,that of a child one,their
        attributes and contents respectively expressed;returns a new entity formed
        by the two nodes - in other words the child folded in the parent.
        Wrapper around buildnode

        """

        tmparent = parent
        tmpnode = node
        tmparent = self.buildnode(parent,1,attrib = pattrib,content = pcontent)
        tmpnode = self.buildnode(node,0,attrib = nattrib, content = ncontent)
        node = tmparent[0] + pcontent + tmpnode + tmparent[2]
        return node

     def buildcdata(self, text):

        """
        Returns a CDATA section out of a string.

        """

        cdata = text
        return '<!CDATA[' + cdata + ']]>'

     def buildcomment(self, text, center=0):

        """
        Returns a comment out of a string.

        """

        comment = text
        return '<!--' + comment + '-->'


     def appendnode(self, node, tree):
         """
         Appends a node - without interpolation - to the XMLFetch's classdict
         returns True if the node has been inserted,and ValueError if it is not.
         (This happens usually if the mapping that holds the nodes itself has been
         altered to be read-only.)

         """

         if node is not StringTypes:
            tmpnode = str(node)
            node = tmpnode
         else :
              pass
         self.__dict__[nodes].append(node)
         return node in self.__dict__[nodes]

     def getnodesfromdict(self):

         """
         Acquires the node list from self.__dict__ .

         """

         nodelist = []
         for node in self.__dict__[nodes]:
            nodelist.append(node)
            return nodelist

     def composeXML(self, tree, add_decl=1):

        """
        Retrieves a XML tree previously defined elsewhere and declaration is added
        if add_decl is 1.

        """

        worktree = tree
        tmptree = str(getnodes())
        if add_decl == 0:
            decl = self._gendecl()
            tree = decl + tmptree
        else: tree = worktree
        return tree


     def XMLtoFileObject(self, fname, tree=None):

        """
        Gets as arguments a filename and a tree then writes the tree to a file with
        the given filename.Returns true if everything has been accomplished
        correctly.A IO error is also raised in the bad case.

        """

        try :
            import os.path
            xmlworktree = tree
            if os.path.exists(fname):
                xmlobj = file(fname,mode='ab+')
            else:
                xmlobj = file(fname,mode='wb+')
            xmlobj.write(xmlworktree)
            xmlobj.close()
            return True
        except ImportError:
            raise ImportError, "os.path missing or behaving uncorrectly.Review your \
        Python's version notes"

I feel to be still very far to write a general-purpose code starting from this but the bulk functionalities are implemented and (almost completely) tested,so making use of it is at your choice.Please let me know your impressions if you try this one.