summaryrefslogtreecommitdiffstats
path: root/chitin/utils.py
blob: be6b4d02ce8b1ebe635d7083d62e586e9e10647f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

import re

def attrsfilter(elements,keywords,operation='or'):
   """
   Function to filter elements by its attributes

   @param   elements      A list of elements to be filtered	
   @param   keywords      A dictionary containing required tags and its values
   @param   operation     A string, either 'or' or 'and', for operation selection

   @return              A list of filtered elements by attributes
   """
   retval = []
   if not keywords: return elements
   if operation == 'or':
       for element in elements:
           for key in keywords:
               if element.attrib.has_key(key):
                  if element.attrib[key] == keywords[key]:
                     retval.append(element)
                     break
   elif operation == 'and':
       for element in elements:
           for key in keywords:
               if not element.attrib.has_key(key): break
               if element.attrib[key] != keywords[key]: break
           retval.append(element)
   return retval

def get_element_tag(element):
    """
    Function to get the element tag without namespace

    @param   element    An element which will be extracted the tag name

    @return             A string, containing the tag name without namespace
    """
    tag = re.match('{.*?}(.*)',element.tag)
    if tag:
       return tag.group(1)
    else:
       return tag

def get_child_value(element,childname):
    """
    Function to get the value of an element's child element

    @param  element    An element to be queried
    @param  childname  A string, containing the tagname of the child

    @return            A string containing child's text value if child is a leaf element, 
                       or a ElementTree element if child is a parent to 1 or more elements
    """
    for c in element.getchildren():
        if get_element_tag(c) == childname:
           if c.getchildren():
             return c
           else:
             return c.text