Project

General

Profile

1 86 aaronmk
# XML "function" nodes that evaluate their contents to text
2
3
import xml_dom
4
5
def map_items(func, items):
6
    return [(name, func(value)) for name, value in items]
7
8
def range_(items):
9
    items = dict(map_items(float, items))
10
    return str(items['to'] - items['from'])
11
12
def avg(items):
13
    count = 0
14
    sum_ = 0.
15
    for name, value in map_items(float, items):
16
        count += 1
17
        sum_ += value
18
    return str(sum_/count)
19
20
def date(items):
21
    items = dict(items)
22 90 aaronmk
    return '-'.join([items['year'], items.get('month', '1'),
23 86 aaronmk
        items.get('day', '1')])
24
25 89 aaronmk
def name(items):
26
    items = dict(items)
27
    return ' '.join([items['first'], items['last']])
28
29 86 aaronmk
# Function names must start with _ to avoid collisions with real tags
30
# Functions have take arguments (doc, node)
31 89 aaronmk
funcs = {'_range': range_, '_avg': avg, '_date': date, '_name': name}
32 86 aaronmk
33
def process(doc, node=None):
34
    if node == None: node = doc.documentElement
35
    name = xml_dom.name_of(node)
36
    if name in funcs: xml_dom.replace_with_text(doc, node,
37
        funcs[name](xml_dom.NodeTextEntryIter(node)))
38
    else:
39
        for child in xml_dom.NodeElemIter(node): process(doc, child)