22
22
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23
23
24
24
"""xmlunwrap - general methods to unwrap XML elements & attributes"""
25
+ from xml .dom .minidom import Element
25
26
26
27
import six
27
28
28
29
class XmlUnwrapError (Exception ):
29
30
pass
30
31
31
- def getText (nodelist ):
32
+ def getText (element ):
33
+ # type:(Element) -> str
34
+ """Return the text of the element as stripped string"""
32
35
rc = ""
33
36
34
- for node in nodelist .childNodes :
37
+ for node in element .childNodes :
35
38
if node .nodeType == node .TEXT_NODE :
36
39
rc = rc + node .data
37
40
if not isinstance (rc , str ): # Python 2 only, otherwise it would return unicode
@@ -47,6 +50,7 @@ def getElementsByTagName(el, tags, mandatory = False):
47
50
return matching
48
51
49
52
def getStrAttribute (el , attrs , default = '' , mandatory = False ):
53
+ # type:(Element, list, str | None, bool) -> str | None
50
54
matching = []
51
55
for attr in attrs :
52
56
val = el .getAttribute (attr )
@@ -59,30 +63,34 @@ def getStrAttribute(el, attrs, default='', mandatory=False):
59
63
return matching [0 ]
60
64
61
65
def getBoolAttribute (el , attrs , default = None ):
66
+ # type:(Element, list, bool | None) -> bool | None
62
67
mandatory = (default == None )
63
- val = getStrAttribute (el , attrs , '' , mandatory ).lower ()
68
+ # Will raise an exception if attribute is not found and default is None:
69
+ val = getStrAttribute (el , attrs , '' , mandatory ).lower () # type: ignore
64
70
if val == '' :
65
71
return default
66
72
return val in ['yes' , 'true' ]
67
73
68
74
def getIntAttribute (el , attrs , default = None ):
75
+ # type:(Element, list, int | None) -> int | None
69
76
mandatory = (default == None )
70
77
val = getStrAttribute (el , attrs , '' , mandatory )
71
78
if val == '' :
72
79
return default
73
80
try :
74
- int_val = int (val , 0 )
81
+ int_val = int (val , 0 ) # type: ignore # (handled by raising XmlUnwarpError below)
75
82
except Exception as e :
76
83
six .raise_from (XmlUnwrapError ("Invalid integer value for %s" % attrs [0 ]), e )
77
84
return int_val
78
85
79
86
def getMapAttribute (el , attrs , mapping , default = None ):
87
+ # type:(Element, list, list[list], str | None) -> str
80
88
mandatory = (default == None )
81
89
k , v = zip (* mapping )
82
90
key = getStrAttribute (el , attrs , default , mandatory )
83
91
84
92
if key not in k :
85
- raise XmlUnwrapError ("Unexpected key %s for attribute" % key )
93
+ raise XmlUnwrapError ("Unexpected key " + str ( key ) + " for attribute" )
86
94
87
95
k_list = list (k )
88
96
return v [k_list .index (key )]
0 commit comments