import re


def ParseAndroidResourceStringsFromXml(xml_data):
  """Parse and Android xml resource file and extract strings from it.

  Args:
    xml_data: XML file data.
  Returns:
    A (dict, namespaces) tuple, where |dict| maps string names to their UTF-8
    encoded value, and |namespaces| is a dictionary mapping prefixes to URLs
    corresponding to namespaces declared in the <resources> element.
  """
  # NOTE: This uses regular expression matching because parsing with something
  # like ElementTree makes it tedious to properly parse some of the structured
  # text found in string resources, e.g.:
  #      <string msgid="3300176832234831527" \
  #         name="abc_shareactionprovider_share_with_application">\
  #             "Condividi tramite <ns1:g id="APPLICATION_NAME">%s</ns1:g>"\
  #      </string>
  result = {}

  # Find <resources> start tag and extract namespaces from it.
  m = re.search('<resources([^>]*)>', xml_data, re.MULTILINE)
  if not m:
    raise Exception('<resources> start tag expected: ' + xml_data)
  input_data = xml_data[m.end():]
  resource_attrs = m.group(1)
  re_namespace = re.compile('\s*(xmlns:(\w+)="([^"]+)")')
  namespaces = {}
  while resource_attrs:
    m = re_namespace.match(resource_attrs)
    if not m:
      break
    namespaces[m.group(2)] = m.group(3)
    resource_attrs = resource_attrs[m.end(1):]

  # Find each string element now.
  re_string_element_start = re.compile('<string ([^>]* )?name="([^">]+)"[^>]*>')
  re_string_element_end = re.compile('</string>')
  while input_data:
    m = re_string_element_start.search(input_data)
    if not m:
      break
    name = m.group(2)
    input_data = input_data[m.end():]
    m2 = re_string_element_end.search(input_data)
    if not m2:
      raise Exception('Expected closing string tag: ' + input_data)
    text = input_data[:m2.start()]
    input_data = input_data[m2.end():]
    if len(text) and text[0] == '"' and text[-1] == '"':
      text = text[1:-1]
    result[name] = text

  return result, namespaces