{% set entries = craft.entries.section( 'databases' ).orderBy( 'title' ) %}
{% header "Content-type: text/xml" %}
{% apply spaceless %}
  <databases>
    {% for entry in entries.all() %}
      {% set group = entry.database.one() %}
      {% for db in group.database.all() %}
        {% set authorization = db.authorization
          ? 'true'
          : 'false' %}
        {% set expires = ( db.expires )
          ? db.expires | date
          : '' %}
        {% set expired = ( db.expires > now | date )
          ? 'true'
          : '' %}
        <database>
          <grouptitle>{{ entry.title|replace('&', '&amp;') }}</grouptitle>
          <groupalternatename>{{ group.alternateName|replace('&', '&amp;') }}</groupalternatename>
          <product>{{ db.product|replace('&', '&amp;') }}</product>
          <address>{{ db.address|replace('&', '&amp;') }}</address>
          <addressremote>{{ db.addressRemote|replace('&', '&amp;') }}</addressremote>
          <authorization>{{ authorization }}</authorization>
          <access>{{ db.access }}</access>
          <expires>{{ expires }}</expires>
          <expired>{{ expired }}</expired>
          {{ _self.categories(entry, 'ageGroup') }}
          {{ _self.categories(entry, 'research') }}
        </database>
      {% endfor %}
    {% endfor %}
  </databases>
{% endapply %}

{% macro categories( entry, category ) %}
  {% for type, values in entry %}
    {% if type == category %}
      <category type="{{ category }}">
        {% for value in values.all() %}
          <{{ category }}>{{ value.title }}</{{ category }}>
        {% endfor %}
      </category>
    {% endif %}
  {% endfor %}
{% endmacro %}
