Package ndg :: Package xacml :: Package utils :: Module xpath_selector
[hide private]

Source Code for Module ndg.xacml.utils.xpath_selector

 1  """XPath selection for XACML AttributeSelector 
 2  """ 
 3  __author__ = "R B Wilkinson" 
 4  __date__ = "23/12/11" 
 5  __copyright__ = "(C) 2011 Science and Technology Facilities Council" 
 6  __license__ = "BSD - see LICENSE file in top-level directory" 
 7  __contact__ = "Philip.Kershaw@stfc.ac.uk" 
 8  __revision__ = "$Id$" 
 9   
10  from abc import ABCMeta, abstractmethod 
11   
12  from ndg.xacml import Config, importElementTree 
13  ElementTree = importElementTree() 
14 15 -class XPathSelectorInterface(object):
16 """Interface for XPath selectors. 17 """ 18 __metaclass__ = ABCMeta 19 20 @abstractmethod
21 - def __init__(self, contextElem):
22 """ 23 @type contextElem: type of an XML element appropriate to implementation 24 @param contextElem: context element on which searches are based 25 """ 26 pass
27 28 @abstractmethod
29 - def selectText(self, path):
30 """Performs an XPath search and returns text content of matched 31 elements. 32 @type path: str 33 @param path: XPath path expression 34 @rtype: list of basestr 35 @return: text from selected elements 36 """ 37 pass
38
39 -class EtreeXPathSelector(XPathSelectorInterface):
40 """XPathSelectorInterface using ElementTree XPath selection. 41 """
42 - def __init__(self, contextElem):
43 """ 44 @type contextElem: ElementTree.Element 45 @param contextElem: context element on which searches are based 46 """ 47 if not ElementTree.iselement(contextElem): 48 raise TypeError("Expecting %r input type for parsing; got %r" % 49 (ElementTree.Element, contextElem)) 50 self.contextElem = contextElem
51 52 if Config.use_lxml:
53 - def selectText(self, path):
54 """Performs an XPath search and returns text content of matched 55 elements. 56 @type path: str 57 @param path: XPath path expression 58 @rtype: list of basestring 59 @return: text from selected elements 60 """ 61 # ElementTree XPath doesn't support absolute paths. Make it relative 62 # to context element. 63 if path.startswith('/'): 64 relPath = '.' + path 65 else: 66 relPath = path 67 find = ElementTree.ETXPath(relPath) 68 elems = find(self.contextElem) 69 returnList = [] 70 for m in elems: 71 # Allow for XPath expression selecting element text or attribute 72 # values. 73 if hasattr(m, 'text'): 74 returnList.append(m.text) 75 else: 76 returnList.append(m.__str__()) 77 return returnList
78 else:
79 - def selectText(self, path):
80 """Performs an XPath search and returns text content of matched 81 elements. 82 @type path: str 83 @param path: XPath path expression 84 @rtype: list of basestring 85 @return: text from selected elements 86 """ 87 # ElementTree XPath doesn't support absolute paths. Make it relative 88 # to context element. 89 if path.startswith('/'): 90 relPath = '.' + path 91 else: 92 relPath = path 93 elems = self.contextElem.findall(relPath) 94 return [e.text for e in elems]
95