Project

General

Profile

1
# 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
    return ' '.join([items['year'], items.get('month', '1'),
23
        items.get('day', '1')])
24

    
25
def name(items):
26
    items = dict(items)
27
    return ' '.join([items['first'], items['last']])
28

    
29
# Function names must start with _ to avoid collisions with real tags
30
# Functions have take arguments (doc, node)
31
funcs = {'_range': range_, '_avg': avg, '_date': date, '_name': name}
32

    
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)
(9-9/10)