Revision 1992
Added by Aaron Marcuse-Kubitza almost 13 years ago
lib/xml_func.py | ||
---|---|---|
27 | 27 |
def __init__(self, cause): |
28 | 28 |
exc.ExceptionWithCause.__init__(self, 'Invalid input value', cause) |
29 | 29 |
|
30 |
##### Functions
|
|
30 |
##### Helper functions
|
|
31 | 31 |
|
32 |
def map_items(func, items): |
|
33 |
return [(name, func(value)) for name, value in items] |
|
34 |
|
|
35 |
def cast(type_, val): |
|
36 |
'''Throws FormatException if can't cast''' |
|
37 |
try: return type_(val) |
|
38 |
except ValueError, e: raise FormatException(e) |
|
39 |
|
|
40 |
def conv_items(type_, items): |
|
41 |
return map_items(lambda val: cast(type_, val), |
|
42 |
xml_dom.TextEntryOnlyIter(items)) |
|
43 |
|
|
44 |
def pop_value(items, name='value'): |
|
45 |
'''@param name Name of value param, or None to accept any name''' |
|
46 |
try: last = items.pop() # last entry contains value |
|
47 |
except IndexError: return None # input is empty and no actions |
|
48 |
if name != None and last[0] != name: return None # input is empty |
|
49 |
return last[1] |
|
50 |
|
|
32 | 51 |
funcs = {} |
33 | 52 |
|
53 |
##### Public functions |
|
54 |
|
|
34 | 55 |
def process(node, on_error=exc.raise_): |
35 | 56 |
for child in xml_dom.NodeElemIter(node): process(child, on_error) |
36 | 57 |
name = node.tagName |
... | ... | |
48 | 69 |
|
49 | 70 |
on_error(e) |
50 | 71 |
|
51 |
def map_items(func, items): |
|
52 |
return [(name, func(value)) for name, value in items] |
|
72 |
def strip(node): |
|
73 |
'''Replaces every XML function with its last parameter (which is usually its |
|
74 |
value)''' |
|
75 |
for child in xml_dom.NodeElemIter(node): strip(child) |
|
76 |
name = node.tagName |
|
77 |
if name.startswith('_') and name in funcs: |
|
78 |
value = pop_value(list(xml_dom.NodeTextEntryIter(node)), name=None) |
|
79 |
xml_dom.replace_with_text(node, value) |
|
53 | 80 |
|
54 |
def cast(type_, val): |
|
55 |
'''Throws FormatException if can't cast''' |
|
56 |
try: return type_(val) |
|
57 |
except ValueError, e: raise FormatException(e) |
|
58 |
|
|
59 |
def conv_items(type_, items): |
|
60 |
return map_items(lambda val: cast(type_, val), |
|
61 |
xml_dom.TextEntryOnlyIter(items)) |
|
62 |
|
|
63 |
def pop_value(items): |
|
64 |
try: last = items.pop() # last entry contains value |
|
65 |
except IndexError: return None # input is empty and no actions |
|
66 |
if last[0] != 'value': return None # input is empty |
|
67 |
return last[1] |
|
68 |
|
|
69 | 81 |
##### XML functions |
70 | 82 |
|
71 | 83 |
# Function names must start with _ to avoid collisions with real tags |
Also available in: Unified diff
xml_func.py: Added strip(). pop_value(): Support custom name of value param.