Statistics
| Branch: | Tag: | Revision:

root / ncclient / content / parsers.py @ d0452bd7

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