1 # Copyright 2009 Shikhar Bhushan
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
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.
21 from cStringIO import StringIO
22 from xml.etree import cElementTree as ET
24 from ncclient import NCClientError
26 class ContentError(NCClientError):
27 "Raised by methods of the :mod:`content` module in case of an error."
32 #: Base NETCONF namespace
33 BASE_NS_1_0 = 'urn:ietf:params:xml:ns:netconf:base:1.0'
34 #: ... and this is BASE_NS according to Cisco devices tested
35 CISCO_BS_1_0 = 'urn:ietf:params:netconf:base:1.0'
36 #: namespace for Tail-f data model
37 TAILF_AAA_1_1 = 'http://tail-f.com/ns/aaa/1.1'
38 #: namespace for Tail-f data model
39 TAILF_EXECD_1_1 = 'http://tail-f.com/ns/execd/1.1'
40 #: namespace for Cisco data model
41 CISCO_CPI_1_0 = 'http://www.cisco.com/cpi_10/schema'
42 #: namespace for Flowmon data model
43 FLOWMON_1_0 = 'http://www.liberouter.org/ns/netopeer/flowmon/1.0'
46 register_namespace = ET.register_namespace
47 except AttributeError:
48 def register_namespace(prefix, uri):
49 from xml.etree import ElementTree
50 # cElementTree uses ElementTree's _namespace_map, so that's ok
51 ElementTree._namespace_map[uri] = prefix
56 TAILF_EXECD_1_1: 'execd',
61 for (ns, pre) in prefix_map.items():
62 register_namespace(pre, ns)
64 qualify = lambda tag, ns=BASE_NS_1_0: tag if ns is None else '{%s}%s' % (ns, tag)
66 multiqualify = lambda tag, nslist=(BASE_NS_1_0, CISCO_BS_1_0): [qualify(tag, ns) for ns in nslist]
68 unqualify = lambda tag: tag[tag.rfind('}')+1:]
70 ### XML representations
76 """DictTree -> Element
78 :type spec: :obj:`dict` or :obj:`string` or :class:`~xml.etree.ElementTree.Element`
80 :rtype: :class:`~xml.etree.ElementTree.Element`
84 elif isinstance(spec, basestring):
85 return XML.Element(spec)
86 if not isinstance(spec, dict):
87 raise ContentError("Invalid tree spec")
89 ele = ET.Element(spec.get('tag'), spec.get('attrib', {}))
90 ele.text = spec.get('text', '')
91 ele.tail = spec.get('tail', '')
92 subtree = spec.get('subtree', [])
93 # might not be properly specified as list but may be dict
94 if not isinstance(subtree, list):
96 for subele in subtree:
97 ele.append(DictTree.Element(subele))
99 elif 'comment' in spec:
100 return ET.Comment(spec.get('comment'))
102 raise ContentError('Invalid tree spec')
105 def XML(spec, encoding='UTF-8'):
108 :type spec: :obj:`dict` or :obj:`string` or :class:`~xml.etree.ElementTree.Element`
110 :arg encoding: chraracter encoding
114 return Element.XML(DictTree.Element(spec), encoding)
120 """DictTree -> Element
122 :type spec: :class:`~xml.etree.ElementTree.Element`
127 'attributes': ele.attrib,
130 'subtree': [ Element.DictTree(child) for child in ele.getchildren() ]
134 def XML(ele, encoding='UTF-8'):
137 :type spec: :class:`~xml.etree.ElementTree.Element`
138 :arg encoding: character encoding
139 :rtype: :obj:`string`
141 xml = ET.tostring(ele, encoding)
142 if xml.startswith('<?xml'):
145 return '<?xml version="1.0" encoding="%s"?>%s' % (encoding, xml)
153 :type spec: :obj:`string`
156 return Element.DictTree(XML.Element(xml))
162 :type xml: :obj:`string`
163 :rtype: :class:`~xml.etree.ElementTree.Element`
165 return ET.fromstring(xml)
167 dtree2ele = DictTree.Element
168 dtree2xml = DictTree.XML
169 ele2dtree = Element.DictTree
170 ele2xml = Element.XML
171 xml2dtree = XML.DictTree
172 xml2ele = XML.Element
174 ### Other utility functions
176 iselement = ET.iselement
179 NSLIST = [BASE_NS_1_0, CISCO_BS_1_0]
181 def find(ele, tag, nslist=[]):
182 """If *nslist* is empty, same as :meth:`xml.etree.ElementTree.Element.find`.
183 If it is not, *tag* is interpreted as an unqualified name and qualified
184 using each item in *nslist* (with a :const:`None` item in *nslit* meaning no
185 qualification is done). The first match is returned.
187 :arg nslist: optional list of namespaces
188 :type nslit: `string` `list`
191 for qname in multiqualify(tag):
192 found = ele.find(qname)
193 if found is not None:
199 """Efficiently parses the root element of an XML document.
201 :arg raw: XML document
203 :returns: a tuple of `(tag, attributes)`, where `tag` is the (qualified) name of the element and `attributes` is a dictionary of its attributes.
206 fp = StringIO(raw[:1024]) # this is a guess but start element beyond 1024 bytes would be a bit absurd
207 for event, element in ET.iterparse(fp, events=('start',)):
208 return (element.tag, element.attrib)
210 def validated_element(rep, tags=None, attrs=None, text=None):
211 """Checks if the root element meets the supplied criteria. Returns a
212 :class:`~xml.etree.ElementTree.Element` instance if so, otherwise raises
215 :arg tags: tag name or a list of allowable tag names
216 :arg attrs: list of required attribute names, each item may be a list of allowable alternatives
217 :arg text: textual content to match
218 :type rep: :obj:`dict` or :obj:`string` or :class:`~xml.etree.ElementTree.Element`
223 if isinstance(tags, basestring):
225 if ele.tag not in tags:
229 if isinstance(req, basestring): req = [req]
231 if alt in ele.attrib:
235 if text and ele.text != text:
238 raise ContentError("Element [%s] does not meet requirements" % ele.tag)