Statistics
| Branch: | Tag: | Revision:

root / ncclient / content / parsers.py @ 1dd43130

History | View | Annotate | Download (2.4 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 ElementTree
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 == _('hello', BASE_NS):
28
            for child in root.getchildren():
29
                if child.tag == _('session-id', BASE_NS):
30
                    sid = child.text
31
                elif child.tag == _('capabilities', BASE_NS):
32
                    for cap in child.getiterator(_('capability', BASE_NS)):
33
                        capabilities.append(cap.text)
34
        return sid, capabilities
35

    
36

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