source: cows/trunk/cows/pylons/genshi_util.py @ 4912

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/cows/trunk/cows/pylons/genshi_util.py@5132
Revision 4912, 1.6 KB checked in by spascoe, 11 years ago (diff)

Added LICENSE file and a short banner at the top of each python file.
Use add_license.py to add a license to new files.

NOTE: also contains a couple of files missed at last commit.

Line 
1# BSD Licence
2# Copyright (c) 2009, Science & Technology Facilities Council (STFC)
3# All rights reserved.
4#
5# See the LICENSE file in the source distribution of this software for
6# the full license text.
7
8"""
9Utilities for use with genshi
10
11@author: Stephen Pascoe
12
13"""
14
15from genshi import *
16
17class RenameElementFilter(object):
18    """
19    Rename the root element in the stream.
20
21    Filters of this class will replicate the stream until the first START event
22    then change the event element's QName.  It will then count opening and closing
23    tags until it finds the matching close tag and replace the QName in that.  It
24    then continues to replicate the stream.
25
26    """
27
28    def __init__(self, newQName):
29        self.newQName = newQName
30        # status 0: awaiting START, 1: awaiting END, 2: noop
31        self.status = 0
32        self.tcount = 0
33
34    def __call__(self, stream):
35        for kind, data, pos in stream:
36            if self.status == 0:
37                if kind == Stream.START:
38                    self.status = 1
39                    self.tcount = 1
40                    yield kind, (self.newQName, data[1]), pos
41                else:
42                    yield kind, data, pos
43            elif self.status == 1:
44                if kind == Stream.START:
45                    self.tcount += 1
46                elif kind == Stream.END:
47                    self.tcount -= 1
48
49                if self.tcount == 0:
50                    self.status == 2
51                    yield kind, self.newQName, pos
52                else:
53                    yield kind, data, pos
54            elif self.status == 2:
55                yield kind, data, pos
Note: See TracBrowser for help on using the repository browser.