Statistics
| Branch: | Tag: | Revision:

root / ncclient / content / parsers.py @ f5c75f88

History | View | Annotate | Download (2.5 kB)

1
# Copyright 2009 Shikhar Bhushan
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License");
4
# you may not use this file except in compliance with the License.
5
# You may obtain a copy of the License at
6
#
7
#    http://www.apache.org/licenses/LICENSE-2.0
8
#
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14

    
15
from xml.etree import cElementTree as ET
16

    
17
from common import BASE_NS
18
from common import qualify as _
19

    
20
class HelloParser:
21

    
22
    @staticmethod
23
    def parse(raw):
24
        'Returns tuple of (session-id, ["capability_uri", ...])'
25
        sid, capabilities = 0, []
26
        root = ET.fromstring(raw)
27
        if root.tag in ('hello', _('hello', BASE_NS)):
28
            for child in root.getchildren():
29
                if child.tag in ('session-id', _('session-id', BASE_NS)):
30
                    sid = child.text
31
                elif child.tag in ('capabilities', _('capabilities', BASE_NS)):
32
                    for cap in child.getiterator('capability'): 
33
                        capabilities.append(cap.text)
34
                    for cap in child.getiterator(_('capability', BASE_NS)):
35
                        capabilities.append(cap.text)
36
        return sid, capabilities
37

    
38

    
39
class RootParser:
40
    '''Parser for the top-level element of an XML document. Does not look at any
41
    sub-elements. It is useful for efficiently determining the type of received
42
    messages.
43
    '''
44
    
45
    def __init__(self, recognize=[]):
46
        self._recognized = recognize
47
    
48
    def recognize(self, element):
49
        '''Specify an element that should be successfully parsed.
50
        
51
        element should be a string that represents a qualified name of the form
52
        `{namespace}tag`.
53
        '''
54
        self._recognized.append(element)
55
    
56
    def parse(self, raw):
57
        '''Parse the top-level element from a string representing an XML document.
58
        
59
        Returns a `(tag, attributes)` tuple, where `tag` is a string representing
60
        the qualified name of the recognized element and `attributes` is an
61
        `{attribute: value}` dictionary.
62
        '''
63
        fp = StringIO(raw)
64
        for event, element in ET.iterparse(fp, events=('start',)):
65
            for ele in self._recognized:
66
                if element.tag == ele:
67
                    return (element.tag, element.attrib)
68
            break
69
        return None