1# Copyright 2016 Google LLC. All Rights Reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14# -*- coding: utf-8 -*- # 15"""Contains some functions that come in handy with XML parsing.""" 16 17from __future__ import absolute_import 18from __future__ import division 19from __future__ import unicode_literals 20 21 22def GetTag(node): 23 """Strips namespace prefix.""" 24 return node.tag.rsplit('}', 1)[-1] 25 26 27def GetChild(node, tag): 28 """Returns first child of node with tag.""" 29 for child in node.getchildren(): 30 if GetTag(child) == tag: 31 return child 32 33 34def BooleanValue(node_text): 35 return node_text.lower() in ('1', 'true') 36 37 38def GetAttribute(node, attr): 39 """Wrapper function to retrieve attributes from XML nodes.""" 40 return node.attrib.get(attr, '') 41 42 43def GetChildNodeText(node, child_tag, default=''): 44 """Finds child xml node with desired tag and returns its text.""" 45 for child in node.getchildren(): 46 if GetTag(child) == child_tag: 47 return GetNodeText(child) or default 48 return default 49 50 51def GetNodeText(node): 52 """Returns the node text after stripping whitespace.""" 53 # Note for empty nodes (like <node></node>) node.text returns None. 54 return node.text.strip() if node.text else '' 55 56 57def GetNodes(node, match_tag): 58 """Gets all children of a node with the desired tag.""" 59 return (child for child in node.getchildren() if GetTag(child) == match_tag) 60