Package lxml :: Module ElementInclude
[hide private]
[frames] | no frames]

Source Code for Module lxml.ElementInclude

  1  # 
  2  # ElementTree 
  3  # $Id: ElementInclude.py 1862 2004-06-18 07:31:02Z Fredrik $ 
  4  # 
  5  # limited xinclude support for element trees 
  6  # 
  7  # history: 
  8  # 2003-08-15 fl   created 
  9  # 2003-11-14 fl   fixed default loader 
 10  # 
 11  # Copyright (c) 2003-2004 by Fredrik Lundh.  All rights reserved. 
 12  # 
 13  # fredrik@pythonware.com 
 14  # http://www.pythonware.com 
 15  # 
 16  # -------------------------------------------------------------------- 
 17  # The ElementTree toolkit is 
 18  # 
 19  # Copyright (c) 1999-2004 by Fredrik Lundh 
 20  # 
 21  # By obtaining, using, and/or copying this software and/or its 
 22  # associated documentation, you agree that you have read, understood, 
 23  # and will comply with the following terms and conditions: 
 24  # 
 25  # Permission to use, copy, modify, and distribute this software and 
 26  # its associated documentation for any purpose and without fee is 
 27  # hereby granted, provided that the above copyright notice appears in 
 28  # all copies, and that both that copyright notice and this permission 
 29  # notice appear in supporting documentation, and that the name of 
 30  # Secret Labs AB or the author not be used in advertising or publicity 
 31  # pertaining to distribution of the software without specific, written 
 32  # prior permission. 
 33  # 
 34  # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD 
 35  # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- 
 36  # ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR 
 37  # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY 
 38  # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, 
 39  # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS 
 40  # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
 41  # OF THIS SOFTWARE. 
 42  # -------------------------------------------------------------------- 
 43   
 44  ## 
 45  # Limited XInclude support for the ElementTree package. 
 46  ## 
 47   
 48  import copy, etree 
 49  from urlparse import urljoin 
 50   
 51  try: 
 52      set 
 53  except NameError: 
 54      from sets import Set as set 
 55   
 56  XINCLUDE = "{http://www.w3.org/2001/XInclude}" 
 57   
 58  XINCLUDE_INCLUDE = XINCLUDE + "include" 
 59  XINCLUDE_FALLBACK = XINCLUDE + "fallback" 
 60   
 61  ## 
 62  # Fatal include error. 
 63   
64 -class FatalIncludeError(etree.LxmlSyntaxError):
65 pass
66 67 ## 68 # ET compatible default loader. 69 # This loader reads an included resource from disk. 70 # 71 # @param href Resource reference. 72 # @param parse Parse mode. Either "xml" or "text". 73 # @param encoding Optional text encoding. 74 # @return The expanded resource. If the parse mode is "xml", this 75 # is an ElementTree instance. If the parse mode is "text", this 76 # is a Unicode string. If the loader fails, it can return None 77 # or raise an IOError exception. 78 # @throws IOError If the loader fails to load the resource. 79
80 -def default_loader(href, parse, encoding=None):
81 file = open(href) 82 if parse == "xml": 83 data = etree.parse(file).getroot() 84 else: 85 data = file.read() 86 if encoding: 87 data = data.decode(encoding) 88 file.close() 89 return data
90 91 ## 92 # Default loader used by lxml.etree - handles custom resolvers properly 93 # 94
95 -def _lxml_default_loader(href, parse, encoding=None, parser=None):
96 if parse == "xml": 97 data = etree.parse(href, parser).getroot() 98 else: 99 data = open(href).read() 100 if encoding: 101 data = data.decode(encoding) 102 return data
103 104 ## 105 # Wrapper for ET compatibility - drops the parser 106
107 -def _wrap_et_loader(loader):
108 def load(href, parse, encoding=None, parser=None): 109 return loader(href, parse, encoding)
110 return load 111 112 113 ## 114 # Expand XInclude directives. 115 # 116 # @param elem Root element. 117 # @param loader Optional resource loader. If omitted, it defaults 118 # to {@link default_loader}. If given, it should be a callable 119 # that implements the same interface as <b>default_loader</b>. 120 # @throws FatalIncludeError If the function fails to include a given 121 # resource, or if the tree contains malformed XInclude elements. 122 # @throws IOError If the function fails to load a given resource. 123 # @returns the node or its replacement if it was an XInclude node 124
125 -def include(elem, loader=None):
126 if hasattr(elem, 'getroot'): 127 tree = elem 128 elem = elem.getroot() 129 else: 130 tree = elem.getroottree() 131 if hasattr(tree, 'docinfo'): 132 base_url = tree.docinfo.URL 133 _include(elem, loader, base_url=base_url)
134
135 -def _include(elem, loader=None, _parent_hrefs=None, base_url=None):
136 if loader is not None: 137 load_include = _wrap_et_loader(loader) 138 else: 139 load_include = _lxml_default_loader 140 141 if _parent_hrefs is None: 142 _parent_hrefs = set() 143 144 parser = elem.getroottree().parser 145 146 include_elements = list( 147 elem.getiterator('{http://www.w3.org/2001/XInclude}*')) 148 149 for e in include_elements: 150 if e.tag == XINCLUDE_INCLUDE: 151 # process xinclude directive 152 href = urljoin(base_url, e.get("href")) 153 parse = e.get("parse", "xml") 154 parent = e.getparent() 155 if parse == "xml": 156 if href in _parent_hrefs: 157 raise FatalIncludeError( 158 "recursive include of %r detected" % href 159 ) 160 _parent_hrefs.add(href) 161 node = load_include(href, parse, parser=parser) 162 if node is None: 163 raise FatalIncludeError( 164 "cannot load %r as %r" % (href, parse) 165 ) 166 node = _include(node, loader, _parent_hrefs) 167 if e.tail: 168 node.tail = (node.tail or "") + e.tail 169 if parent is None: 170 return node # replaced the root node! 171 parent.replace(e, node) 172 elif parse == "text": 173 text = load_include(href, parse, encoding=e.get("encoding")) 174 if text is None: 175 raise FatalIncludeError( 176 "cannot load %r as %r" % (href, parse) 177 ) 178 predecessor = e.getprevious() 179 if predecessor is not None: 180 predecessor.tail = (predecessor.tail or "") + text 181 elif parent is None: 182 return text # replaced the root node! 183 else: 184 parent.text = (parent.text or "") + text + (e.tail or "") 185 parent.remove(e) 186 else: 187 raise FatalIncludeError( 188 "unknown parse type in xi:include tag (%r)" % parse 189 ) 190 elif e.tag == XINCLUDE_FALLBACK: 191 parent = e.getparent() 192 if parent is not None and parent.tag != XINCLUDE_INCLUDE: 193 raise FatalIncludeError( 194 "xi:fallback tag must be child of xi:include (%r)" % e.tag 195 ) 196 else: 197 raise FatalIncludeError( 198 "Invalid element found in XInclude namespace (%r)" % e.tag 199 ) 200 return elem
201