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
# Function names must start with _ to avoid collisions with real tags
26
# Functions have take arguments (doc, node)
27
funcs = {'_range': range_, '_avg': avg, '_date': date}
28

    
29
def process(doc, node=None):
30
    if node == None: node = doc.documentElement
31
    name = xml_dom.name_of(node)
32
    if name in funcs: xml_dom.replace_with_text(doc, node,
33
        funcs[name](xml_dom.NodeTextEntryIter(node)))
34
    else:
35
        for child in xml_dom.NodeElemIter(node): process(doc, child)
(9-9/10)