A
download xmlobject.py
Language: Python
LOC: 437
Project Info
Freenet
Server: FreenetProject.org
Type: svn
...t\trunk\apps\pyFreenet\fcp\
   __init__.py
   fproxyproxy.py
   freenetfs.py
   genkey.py
   get.py
   invertkey.py
   names.py
   node.py
   put.py
   redirect.py
   sitemgr.py
   xmlobject.py
   xmlrpc.py

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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
#@+leo-ver=4
#@+node:@file xmlobject.py
"""
Allows XML files to be operated on like Python objects.

Features:
    - load XML source from file pathnames, readable file objects or raw strings
    - add, get and set tag attributes like with python attributes
    - iterate over nodes
    - save the modified XMLFile or XMLObject to file

Example XML file::

    <?xml version="1.0" encoding="UTF-8"?>
    <rapsheets>
     <person name="John Smith" age="42">
        <!-- John Smith has an appeal in process against his last conviction -->
        <crime name="Armed robbery" date="March 11, 1994"/>
        <crime name="Aggravated burglary" date="June 9, 2001"/>
     </person>
     <person name="Mary Jones" age="33">
        <crime name="Prostitution" date="January 8, 1997"/>
        <crime name="Selling heroin" date="September 4, 2002"/>
        <crime name="Manslaughter" date="December 21, 2004"/>
     </person>
    </rapsheets>

Example usage::

    >>> from xmlobject import XMLFile
    
    >>> x = XMLFile(path="sample.xml)

    >>> print x
    <xmlobj.XMLFile instance at 0xb7ccc52c>

    >>> print x.root
    <XMLNode: rapsheets>

    >>> print x.root._children
    [<XMLNode: text>, <XMLNode: person>, <XMLNode: text>,
     <XMLNode: person>, <XMLNode: text>]

    >>> print x.root.person
    [<XMLNode: person>, <XMLNode: person>]

    >>> print x.root.person[0].name
    John Smith

    >>> john = x.root.person[0]
    
    >>> john.height = 184

    >>> c = john._addNode("crime")

    >>> c.name = "Grand Theft Auto"
    
    >>> c.date = "4 May, 2005"

    >>> print x.toxml()
    <?xml version="1.0" ?>
    <rapsheets>
     <person age="42" height="184" name="John Smith">
        <!-- John Smith has an appeal in process against his last conviction -->
        <crime date="March 11, 1994" name="Armed robbery"/>
        <crime date="June 9, 2001" name="Aggravated burglary"/>
     <crime date="4 May, 2005" name="Grand Theft Auto"/></person>
     <person age="33" name="Mary Jones">
        <crime date="January 8, 1997" name="Prostitution"/>
        <crime date="September 4, 2002" name="Selling heroin"/>
        <crime date="December 21, 2004" name="Manslaughter"/>
     </person>
    </rapsheets>

    >>>

"""

#@+others
#@+node:imports
import sys, os
import xml.dom
import xml.dom.minidom
from xml.dom.minidom import parse, parseString, getDOMImplementation

#@-node:imports
#@+node:globals
impl = getDOMImplementation()

#@-node:globals
#@+node:exceptions
class MissingRootTag(Exception):
    """root tag name was not given"""

class InvalidXML(Exception):
    """failed to parse XML input"""

class CannotSave(Exception):
    """unable to save"""

class InvalidNode(Exception):
    """not a valid minidom node"""

#@-node:exceptions
#@+node:class XMLFile
class XMLFile:
    """
    Allows an xml file to be viewed and operated on
    as a python object.

    (If you're viewing the epydoc-generated HTML documentation, click the 'show private'
    link at the top right of this page to see all the methods)

    Holds the root node in the .root attribute, also in an attribute
    with the same name as this root node.
    """
    #@    @+others
    #@+node:__init__
    def __init__(self, **kw):
        """
        Create an XMLFile
        
        Keywords:
            - path - a pathname from which the file can be read
            - file - an open file object from which the raw xml
              can be read
            - raw - the raw xml itself
            - root - name of root tag, if not reading content
    
        Usage scenarios:
            1. Working with existing content - you must supply input in
               one of the following ways:
                   - 'path' must be an existing file, or
                   - 'file' must be a readable file object, or
                   - 'raw' must contain raw xml as a string
            2. Creating whole new content - you must give the name
               of the root tag in the 'root' keyword
        
        Notes:
            - Keyword precedence governing existing content is:
                1. path (if existing file)
                2. file
                3. raw
            - If working with existing content:
                - if the 'root' is given, then the content's toplevel tag
                  MUST match the value given for 'root'
                - trying to _save will raise an exception unless 'path'
                  has been given
            - if not working with existing content:
                - 'root' must be given
                - _save() will raise an exception unless 'path' has been given
        """
        path = kw.get("path", None)
        fobj = kw.get("file", None)
        raw = kw.get("raw", None)
        root = kw.get("root", None)
        
        if path:
            self.path = path
            try:
                fobj = file(path)
            except IOError:
                pass
        else:
            self.path = None
    
        if fobj:
            raw = fobj.read()
    
        if raw:
            self.dom = xml.dom.minidom.parseString(raw)
        else:
            # could not source content, so create a blank slate
            if not root:
                # in which case, must give a root node name
                raise MissingRootTag(
                        "No existing content, so must specify root")
    
            # ok, create a blank dom
            self.dom = impl.createDocument(None, root, None)
    
        # get the root node, save it as attributes 'root' and name of node
        rootnode = self.dom.documentElement
    
        # now validate root tag
        if root:
            if rootnode.nodeName != root:
                raise IncorrectRootTag("Gave root='%s', input has root='%s'" % (
                    root, rootnode.nodeName))
    
        # need this for recursion in XMLNode
        self._childrenByName = {}
        self._children = []
    
        # add all the child nodes    
        for child in self.dom.childNodes:
            childnode = XMLNode(self, child)
            #print "compare %s to %s" % (rootnode, child)
            if child == rootnode:
                #print "found root"
                self.root = childnode
        setattr(self, rootnode.nodeName, self.root)
    
    #@-node:__init__
    #@+node:save
    def save(self, where=None, obj=None):
        """
        Saves the document.
        
        If argument 'where' is given, saves to it, otherwise
        tries to save to the original given 'path' (or barfs)
        
        Value can be a string (taken to be a file path), or an open
        file object.
        """
        obj = obj or self.dom
    
        if not where:
            if self.path:
                where = self.path
    
        if isinstance(where, str):
            where = file(where, "w")
    
        if not where:
            raise CannotSave("No save destination, and no original path")
    
        where.write(obj.toxml())
        where.flush()
    
    #@-node:save
    #@+node:saveAs
    def saveAs(self, path):
        """
        save this time, and all subsequent times, to filename 'path'
        """
        self.path = path
        self.save()
    
    #@-node:saveAs
    #@+node:toxml
    def toxml(self):
        return self.dom.toxml()
    
    #@-node:toxml
    #@+node:__len__
    def __len__(self):
        """
        returns number of child nodes
        """
        return len(self._children)
    
    #@-node:__len__
    #@+node:__getitem__
    def __getitem__(self, idx):
        if isinstance(idx, int):
            return self._children[idx]
        else:
            return self._childrenByName[idx]
    
    #@-node:__getitem__
    #@-others

#@-node:class XMLFile
#@+node:class XMLNode
class XMLNode:
    """
    This is the workhorse for the xml object interface

    (If you're viewing the epydoc-generated HTML documentation, click the 'show private'
    link at the top right of this page to see all the methods)

    """
    #@    @+others
    #@+node:__init__
    def __init__(self, parent, node):
        """
        You shouldn't need to instantiate this directly
        """
        self._parent = parent
        if isinstance(parent, XMLFile):
            self._root = parent
        else:
            self._root = parent._root
        self._node = node
        self._childrenByName = {}
        self._children = []
    
        # add ourself to parent's children registry
        parent._children.append(self)
    
        # the deal with named subtags is that we store the first instance
        # as itself, and with second and subsequent instances, we make a list
        parentDict = self._parent._childrenByName
        nodeName = node.nodeName
        if not parentDict.has_key(nodeName):
            parentDict[nodeName] = parent.__dict__[nodeName] = self
        else:
            if isinstance(parentDict[nodeName], XMLNode):
                # this is the second child node of a given tag name, so convert
                # the instance to a list
                parentDict[nodeName] = parent.__dict__[nodeName] = [parentDict[nodeName]]
            parentDict[nodeName].append(self)
    
        # figure out our type
        self._value = None
        if isinstance(node, xml.dom.minidom.Text):
            self._type = "text"
            self._value = node.nodeValue
        elif isinstance(node, xml.dom.minidom.Element):
            self._type = "node"
            self._name = nodeName
        elif isinstance(node, xml.dom.minidom.Comment):
            self._type = "comment"
            self._value = node.nodeValue
        else:
            raise InvalidNode("node class %s" % node.__class__)
    
        # and wrap all the child nodes
        for child in node.childNodes:
            XMLNode(self, child)
    
    #@-node:__init__
    #@+node:_render
    def _render(self):
        """
        Produces well-formed XML of this node's contents,
        indented as required
        """
        return self._node.toxml()
    
    #@-node:_render
    #@+node:__repr__
    def __repr__(self):
        if self._type == "node":
            return "<XMLNode: %s>" % self._node.nodeName
        else:
            return "<XMLNode: %s>" % self._type
    
    #@-node:__repr__
    #@+node:__getattr__
    def __getattr__(self, attr):
        """
        Fetches an attribute or child node of this tag
        
        If it's an attribute, then returns the attribute value as a string.
        
        If a child node, then:
            - if there is only one child node of that name, return it
            - if there is more than one child node of that name, return a list
              of child nodes of that tag name
    
        Supports some magic attributes:
            - _text - the value of the first child node of type text
        """
        #print "%s: __getattr__: attr=%s" % (self, attr)
    
        # magic attribute to return text
        if attr == '_text':
            tnode = self['#text']
            if isinstance(tnode, list):
                tnode = tnode[0]
            return tnode._value
    
        if self._type in ['text', 'comment']:
            if attr == '_value':
                return self._node.nodeValue
            else:
                raise AttributeError(attr)
    
        if self._node.hasAttribute(attr):
            return self._node.getAttribute(attr)
        elif self._childrenByName.has_key(attr):
            return self._childrenByName[attr]
        
        #elif attr == 'value':
            # magic attribute
            
        else:
            raise AttributeError(attr)
    
    
    #@-node:__getattr__
    #@+node:__setattr__
    def __setattr__(self, attr, val):
        """
        Change the value of an attribute of this tag
    
        The magic attribute '_text' can be used to set the first child
        text node's value
        
        For example::
            
            Consider:
            
              <somenode>
                <child>foo</child>
              </somenode>
    
            >>> somenode
            <XMLNODE: somenode>
            >>> somenode.child
            <XMLNODE: child>
            >>> somenode.child._text
            'foo'
            >>> somenode._toxml()
            u'<somenode><child>foo</child></somenode>'
            >>> somenode.child._text = 'bar'
            >>> somenode.child._text
            'bar'
            >>> somenode.child._toxml()
            u'<somenode><child>bar/child></somenode>'
            
        """
        if attr.startswith("_"):
    
            # magic attribute for setting _text
            if attr == '_text':
                tnode = self['#text']
                if isinstance(tnode, list):
                    tnode = tnode[0]
                tnode._node.nodeValue = val
                tnode._value = val
                return
                
            self.__dict__[attr] = val
        elif self._type in ['text', 'comment']:
            self._node.nodeValue = val
        else:
            # discern between attribute and child node
            if self._childrenByName.has_key(attr):
                raise Exception("Attribute Exists")
            self._node.setAttribute(attr, str(val))
    
    #@-node:__setattr__
    #@+node:_keys
    def _keys(self):
        """
        Return a list of attribute names
        """
        return self._node.attributes.keys()
    
    def _values(self):
        """
        Returns a list of (attrname, attrval) tuples for this tag
        """
        return [self._node.getAttribute(k) for k in self._node.attributes.keys()]
    
    def _items(self):
        """
        returns a list of attribute values for this tag
        """
        return [(k, self._node.getAttribute(k)) for k in self._node.attributes.keys()]
    
    def _has_key(self, k):
        """
        returns True if this tag has an attribute of the given name
        """
        return self._node.hasAttribute(k) or self._childrenByName.has_key(k)
    
    def _get(self, k, default=None):
        """
        returns the value of attribute k, or default if no such attribute
        """
        if self._has_key(k):
            return getattr(self, k)
        else:
            return default
    #@-node:_keys
    #@+node:__len__
    def __len__(self):
        """
        returns number of child nodes
        """
        return len(self._children)
    
    #@-node:__len__
    #@+node:__getitem__
    def __getitem__(self, idx):
        """
        if given key is numeric, return the nth child, otherwise
        try to return the child tag (or list of child tags) having
        the key as the tag name
        """
        #print "__getitem__: idx=%s" % str(idx)
    
        if isinstance(idx, slice) or isinstance(idx, int):
            return self._children[idx]
        elif isinstance(idx, str):
            return self._childrenByName[idx]
        else:
            raise IndexError(idx)
    
    #@-node:__getitem__
    #@+node:_addNode
    def _addNode(self, child):
        """
        Tries to append a child node to the tree, and returns it
        
        Value of 'child' must be one of:
            - a string (in which case it is taken to be the name
              of the new node's tag)
            - a dom object, in which case it will be wrapped and added
            - an XMLNode object, in which case it will be added without
              wrapping
        """
    
        if isinstance(child, XMLNode):
    
            # add it to our children registry
            self._children.append(child)
    
            parentDict = self._childrenByName
            nodeName = child._node.nodeName
    
            if not parentDict.has_key(nodeName):
                parentDict[nodeName] = self.__dict__[nodeName] = child
            else:
                if isinstance(parentDict[nodeName], XMLNode):
                    # this is the second child node of a given tag name, so convert
                    # the instance to a list
                    parentDict[nodeName] \
                        = self.__dict__[nodeName] \
                            = [parentDict[nodeName]]
    
                parentDict[nodeName].append(child)
    
            # and stick it in the dom
            self._node.appendChild(child._node)
            
            return child
    
        elif isinstance(child, str):
            childNode = self._root.dom.createElement(child)
            self._node.appendChild(childNode)
    
        elif isinstance(child, xml.dom.minidom.Element):
            childNode = child
            child = childNode.nodeName
            self._node.appendChild(childNode)
    
            
        return XMLNode(self, childNode)
    
    #@-node:_addNode
    #@+node:_getChild
    def _getChild(self, name):
        """
        Returns a list of zero or more child nodes whose
        tag name is <name>
        """
        try:
            item = getattr(self, name)
        except AttributeError:
            return []
        
        if not isinstance(item, list):
            item = [item]
        
        return item
    
    #@-node:_getChild
    #@+node:_delChild
    def _delChild(self, child):
        """
        Removes given child node
        """
        node = self
        while True:
            print "Trying to remove %s from %s" % (child, node)
            if child in node._children:
                print "removing"
                node._children.remove(child)
                node._node.removeChild(child._node)
        
            for k,v in node._childrenByName.items():
                if child == v:
                    del node._childrenByName[k]
                elif isinstance(v, list):
                    if child in v:
                        v.remove(child)
            
            if isinstance(node, XMLFile):
                break
            
            node = node._parent
    
    #@-node:_delChild
    #@+node:_addText
    def _addText(self, value):
        """
        Tries to append a child text node, with the given text, to the tree,
        and returns the created node object
        """
        childNode = self._root.dom.createTextNode(value)
        self._node.appendChild(childNode)
        return XMLNode(self, childNode)
    
    #@-node:_addText
    #@+node:_addComment
    def _addComment(self, comment):
        """
        Tries to append a child comment node (with the given text value)
        to the tree, and returns the create node object
        """
        childNode = self._root.dom.createCommentNode(comment)
        self._node.appendChild(childNode)
        return XMLNode(self, childNode)
    
    #@-node:_addComment
    #@+node:_save
    def _save(self, where=None):
        """
        Generates well-formed XML from just this node, and saves it
        to a file.
        
        Argument 'where' is either an open file object, or a pathname
    
        If 'where' is not given, then saves the entire document tree.
        """
        if not where:
            self._root.save()
        else:
            self._root.save(where, self._node)
    
    #@-node:_save
    #@+node:_toxml
    def _toxml(self):
        """
        renders just this node out to raw xml code
        """
        return self._node.toxml()
    
    #@-node:_toxml
    #@-others
#@-node:class XMLNode
#@-others
#@nonl
#@-node:@file xmlobject.py
#@-leo

About Koders | Resources | Downloads | Support | Black Duck | Terms of Service | DMCA | Privacy Policy | Contact Us