Statistics
| Branch: | Tag: | Revision:

root / ncclient / xml_.py @ 9667bcb2

History | View | Annotate | Download (4.1 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

    
16
"""The :mod:`xml` module provides methods for creating XML documents, parsing
17
XML, and converting between different XML representations. It uses
18
:mod:`~xml.etree.ElementTree` internally.
19
"""
20

    
21
from cStringIO import StringIO
22
from xml.etree import cElementTree as ET
23

    
24
from ncclient import NCClientError
25

    
26
class XMLError(NCClientError):
27
    pass
28

    
29
### Namespace-related
30

    
31
#: Base NETCONF namespace
32
BASE_NS_1_0 = 'urn:ietf:params:xml:ns:netconf:base:1.0'
33
#: namespace for Tail-f data model
34
TAILF_AAA_1_1 = 'http://tail-f.com/ns/aaa/1.1'
35
#: namespace for Tail-f data model
36
TAILF_EXECD_1_1 = 'http://tail-f.com/ns/execd/1.1'
37
#: namespace for Cisco data model
38
CISCO_CPI_1_0 = 'http://www.cisco.com/cpi_10/schema'
39
#: namespace for Flowmon data model
40
FLOWMON_1_0 = 'http://www.liberouter.org/ns/netopeer/flowmon/1.0'
41

    
42
try:
43
    register_namespace = ET.register_namespace
44
except AttributeError:
45
    def register_namespace(prefix, uri):
46
        from xml.etree import ElementTree
47
        # cElementTree uses ElementTree's _namespace_map, so that's ok
48
        ElementTree._namespace_map[uri] = prefix
49

    
50
prefix_map = {
51
    BASE_NS_1_0: 'nc',
52
    TAILF_AAA_1_1: 'aaa',
53
    TAILF_EXECD_1_1: 'execd',
54
    CISCO_CPI_1_0: 'cpi',
55
    FLOWMON_1_0: 'fm',
56
}
57

    
58
for (ns, pre) in prefix_map.items():
59
    register_namespace(pre, ns)
60

    
61
qualify = lambda tag, ns=BASE_NS_1_0: tag if ns is None else '{%s}%s' % (ns, tag)
62

    
63
#unqualify = lambda tag: tag[tag.rfind('}')+1:]
64

    
65
def to_xml(ele, encoding="UTF-8"):
66
    """Element -> XML
67
    
68
    :type spec: :class:`~xml.etree.ElementTree.Element`
69
    :arg encoding: character encoding
70
    :rtype: :obj:`string`
71
    """
72
    xml = ET.tostring(ele, encoding)
73
    return xml if xml.startswith('<?xml') else '<?xml version="1.0" encoding="%s"?>%s' % (encoding, xml)
74

    
75
def to_ele(x):
76
    """XML -> Element
77
    
78
    :type xml: :obj:`string`
79
    :rtype: :class:`~xml.etree.ElementTree.Element`
80
    """
81
    return x if iselement(x) else ET.fromstring(x)
82

    
83
iselement = ET.iselement
84

    
85
def parse_root(raw):
86
    """Efficiently parses the root element of an XML document.
87

88
    :arg raw: XML document
89
    :type raw: string
90
    :returns: a tuple of `(tag, attributes)`, where `tag` is the (qualified) name of the element and `attributes` is a dictionary of its attributes.
91
    :rtype: `tuple`
92
    """
93
    fp = StringIO(raw)
94
    for event, element in ET.iterparse(fp, events=('start',)):
95
        return (element.tag, element.attrib)
96

    
97
def validated_element(x, tags=None, attrs=None):
98
    """Checks if the root element meets the supplied criteria. Returns a
99
    :class:`~xml.etree.ElementTree.Element` instance if so, otherwise raises
100
    :exc:`ContentError`.
101

102
    :arg tags: tag name or a sequence of allowable tag names
103
    :arg attrs: sequence of required attribute names, each item may be a list of allowable alternatives
104
    :arg text: textual content to match
105
    :type rep: :class:`~xml.etree.ElementTree.Element`
106
    """
107
    ele = to_ele(x)
108
    if tags:
109
        if isinstance(tags, basestring):
110
            tags = [tags]
111
        if ele.tag not in tags:
112
            raise XMLError("Element [%s] does not meet requirement" % ele.tag)
113
    if attrs:
114
        for req in attrs:
115
            if isinstance(req, basestring): req = [req]
116
            for alt in req:
117
                if alt in ele.attrib:
118
                    break
119
            else:
120
                raise XMLError("Element [%s] does not have required attributes" % ele.tag)
121
    return ele
122

    
123
def new_ele(tag, attrs={}, **extra):
124
    return ET.Element(tag, attrs, **extra)
125

    
126
def sub_ele(parent, tag, attrs={}, **extra):
127
    return ET.SubElement(parent, tag, attrs, **extra)