Package simplexmlapi :: Module api
[hide private]
[frames] | no frames]

Source Code for Module simplexmlapi.api

  1  from node import DotXMLDoc, AttributeParsingError 
  2   
3 -class SimpleXmlApi(object):
4 """ 5 The main API class, comprising a map of attributes to dotted path names. 6 7 Accessing an attribute that has been mapped to a dotted name will return 8 the text value of that node/attribute. If an attribute is passed that 9 isn't in the map, it's passed off to the L{DotXMLDoc} instance, so that 10 the document can be walked manually. 11 12 May be subclassed, overriding C{_map}, to provide custom APIs for known XML 13 structures. 14 """ 15 _map = {} 16 _doc = None 17
18 - def __init__(self, source="", map=None):
19 """ 20 @param source: A string containing an XML document 21 @type source: str 22 @param map: 23 @type map: dict 24 @return: void 25 """ 26 if map is not None: 27 self.load_map(map) 28 self.load_source(source)
29
30 - def add_mapping(self, name, path):
31 """ 32 Add a new attribute - dotted name mapping to the instance's map 33 registry. 34 35 @param name: The name of the attribute. 36 @type name: str 37 @param path: A dotted name that can be traversed. 38 @type path: str 39 @return: void 40 """ 41 self._map[name] = path
42
43 - def load_source(self, source):
44 """ 45 Parse an XML document and set it as this API's target. 46 47 @param source: A string containing an XML document. 48 @type source: str 49 @return: void 50 """ 51 self._doc = DotXMLDoc(source)
52
53 - def load_map(self, map):
54 """ 55 Update the attribute registry with one or more mappings. Will not 56 remove attributes that currently exist. 57 58 @param map: A dictionary of the form C{\{'attribute':'dotted.name'\}} 59 @type map: dict 60 @return: void 61 """ 62 self._map.update(map)
63
64 - def del_mapping(self, name):
65 """ 66 Remove an attribute mapping from the registry. 67 68 @param name: The name of the attribute to remove from the registry. 69 @type name: str 70 @return: void 71 """ 72 try: del self._map[name] 73 except KeyError: pass
74
75 - def __getattr__(self, attr):
76 try: 77 return self._traverse(self._map[attr]) 78 except KeyError: 79 return getattr(self._doc, attr)
80
81 - def _traverse(self, path):
82 """ 83 Traverse a dotted path against the XML document in memory and return 84 its text value. 85 86 @param path: A dotted path that will resolve to a node or attribute. 87 @type path: str 88 @return: The text value of the node. 89 @rtype: str 90 """ 91 try: 92 return eval("self._doc.%s" % path).getValue() 93 except SyntaxError: 94 raise AttributeParsingError
95 96
97 -def factory(source, map=None, cls=None):
98 """ 99 Create a new L{SimpleXmlApi} instance using the given source and optional 100 attribute map. 101 102 To create an instance of a subclass, pass in the C{cls} attribute. 103 """ 104 if cls is None: 105 cls = SimpleXmlApi 106 return cls(source, map)
107