Adicionada abstração de items.
[cascardo/irpf-gui.git] / src / items.py
1 # coding=utf-8
2 #
3 #   Copyright 2013 Thadeu Lima de Souza Cascardo <cascardo@cascardo.info>
4 #
5 #   This program is free software: you can redistribute it and/or modify
6 #   it under the terms of the GNU General Public License as published by
7 #   the Free Software Foundation, either version 3 of the License, or
8 #   (at your option) any later version.
9 #
10 #   This program is distributed in the hope that it will be useful,
11 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 #   GNU General Public License for more details.
14 #
15 #   You should have received a copy of the GNU General Public License
16 #   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 # -*- mode: python; encoding: utf-8; -*-
18 import xml.dom.minidom
19
20 class Item:
21     def __init__(self, el):
22         self.el = el
23
24     def get_attr(self, attr):
25         if attr in self.el.attributes.keys():
26             return self.el.attributes[attr].nodeValue
27         return None
28
29     def set_attr(self, attr, val):
30         self.el.setAttribute(attr, val)
31
32 class Items:
33     def __init__(self, element):
34         self.element = element
35         self.items = []
36
37         for i in self.element.getElementsByTagName("item"):
38             self.items.append(Item(i))
39
40     def _get_attr(self, el, attr):
41         if attr in el.attributes.keys():
42             return el.attributes[attr].nodeValue
43         return None
44
45     def _set_attr(self, el, attr, val):
46         el.setAttribute(attr, val)
47
48     def get_attr(self, attr):
49         return self._get_attr(self.element, attr)
50
51     def set_attr(self, attr, val):
52         self._set_attr(self.element, attr, val)
53
54     def add_item(self, item):
55         self.items.append(item)
56         self.element.appendChild(item.el)
57
58     def new_item(self):
59         item = Item(self.element.ownerDocument.createElement("item"))
60         self.add_item(item)
61         return item
62
63     def remove_item(self, i):
64         self.items.pop(i)
65         els = self.element.getElementsByTagName("item")
66         self.element.removeChild(els[i])
67
68 if __name__ == '__main__':
69     doc = xml.dom.minidom.DOMImplementation().createDocument("", "doc", "")
70     el = doc.createElement("items")
71
72     items = Items(el)
73     items.new_item().set_attr("value", "0,00")
74     items.set_attr("total", "0,00")
75
76     print items.element.toprettyxml()
77
78     for i in items.items:
79         print i.get_attr("value")
80
81 # vim:tabstop=4:expandtab:smartindent