Tecnologías XML / XSLT / Recetario XSLT / De XML a XML / Convertir elementos en atributos

(Extracto de «XSLT Kochbuch» de Sal Mangano)

Problema

Su documento codifica información mediante elementos hijos, pero preferiría atributos.

Solución

Como en la receta Convertir atributos en elementos, puede utilizar la copia con sustitución. Pero hay que elegir dónde convertir elementos en atributos: convertirlos todos carecería de sentido. Esta hoja invierte la transformación de atributos a elementos de la receta anterior:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:import href="copy.xslt"/>
  <xsl:output method="xml" version="1.0" encoding="UTF-8"/>
  <xsl:template match="person">
    <xsl:copy>
      <xsl:for-each select="*">
        <xsl:attribute name="{local-name(.)}">
          <xsl:value-of select="."/>
        </xsl:attribute>
      </xsl:for-each>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

Discusión

XSLT 1.0

Este sentido es menos sencillo. Si un elemento convertido tiene atributos, hay que decidir qué hacer con ellos. La solución anterior los pierde. Otra posibilidad los transmite al nuevo padre:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:import href="copy.xslt"/>
  <xsl:output method="xml" version="1.0" encoding="UTF-8"/>
  <xsl:template match="person">
    <xsl:copy>
      <xsl:for-each select="*">
        <xsl:attribute name="{local-name(.)}">
          <xsl:value-of select="."/>
        </xsl:attribute>
        <xsl:copy-of select="@*"/>
      </xsl:for-each>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

Solo funciona si todos los nombres de atributos afectados son únicos. De lo contrario, cámbielos, por ejemplo:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:import href="copy.xslt"/>
  <xsl:output method="xml" version="1.0" encoding="UTF-8"/>
  <xsl:template match="person">
    <xsl:copy>
      <xsl:for-each select="*">
        <xsl:attribute name="{local-name(.)}">
          <xsl:value-of select="."/>
        </xsl:attribute>
        <xsl:variable name="elem-name" select="local-name(.)"/>
        <xsl:for-each select="@*">
          <xsl:attribute name="{concat($elem-name,'-',local-name(.))}">
            <xsl:value-of select="."/>
          </xsl:attribute>
        </xsl:for-each>
      </xsl:for-each>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

Los hermanos con nombres repetidos crean otro conflicto al convertirse. Otra estrategia convierte un elemento solo si no tiene atributos ni hijos de elemento, no se repite en su padre y este no tiene atributos:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:import href="copy.xslt"/>
  <xsl:output method="xml" indent="yes" version="1.0" encoding="UTF-8"/>
  <!-- Elemente erfassen, die Eltern sind -->
  <xsl:template match="*[*]">
    <xsl:choose>
      <!-- Kinder nur dann konvertieren, wenn dieses Element selbst keine Attribute besitzt -->
      <xsl:when test="not(@*)">
        <xsl:copy>
          <!-- Kinder in Attribute konvertieren, wenn das Kind keine Kinder oder Attribute besitzt und unter seinen Geschwistern einen eindeutigen Namen trägt -->
          <xsl:for-each select="*">
            <xsl:choose>
              <xsl:when test="not(*) and not(@*) and not(preceding-sibling::*[name( ) = name(current( ))]) and not(following-sibling::*[name( ) = name(current( ))])">
                <xsl:attribute name="{local-name(.)}">
                  <xsl:value-of select="."/>
                </xsl:attribute>
              </xsl:when>
              <xsl:otherwise>
                <xsl:apply-templates select="."/>
              </xsl:otherwise>
            </xsl:choose>
          </xsl:for-each>
        </xsl:copy>
      </xsl:when>
      <xsl:otherwise>
        <xsl:copy>
          <xsl:apply-templates/>
        </xsl:copy>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>

XSLT 2.0

Utilizar xsl:for-each-group simplifica y acelera parcialmente la solución 1.0. El truco es utilizar group-by="name( )" para detectar hermanos con el mismo nombre. También transmite al padre los atributos del elemento convertido, algo posible en 1.0:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:import href="copy.xslt"/>
  <xsl:output method="xml" indent="yes" version="1.0" encoding="UTF-8"/>
  <!-- Elemente erfassen, die Eltern sind -->
  <xsl:template match="*[*]">
    <xsl:choose>
      <!-- Nur Kinder konvertieren, wenn dieses Element keine eigenen Attribute besitzt -->
      <xsl:when test="not(@*)">
        <xsl:copy>
          <!-- Kinder in Attribute umwandeln, wenn das Kind keine Kinder oder Attribute besitzt und unter seinen Geschwistern einen eindeutigen Namen trägt -->
          <xsl:for-each-group select="*" group-by="name( )">
            <xsl:choose>
              <xsl:when test="not(*) and count(current-group( )) eq 1">
                <xsl:attribute name="{local-name(.)}">
                  <xsl:value-of select="."/>
                </xsl:attribute>
                <!-- Attribute des Kindes auf das Elternelement kopieren -->
                <xsl:copy-of select="@*"/>
              </xsl:when>
              <xsl:otherwise>
                <xsl:apply-templates select="current-group( )"/>
              </xsl:otherwise>
            </xsl:choose>
          </xsl:for-each-group>
        </xsl:copy>
      </xsl:when>
      <xsl:otherwise>
        <xsl:copy>
          <xsl:apply-templates select="@*| node( )"/>
        </xsl:copy>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>

Atención:
Ambas hojas suponen una estructura canónica: en cada nivel, todos los elementos convertibles preceden a los demás. Este documento incumple esa suposición:

<E1>
  <E2>
    <e31>a</e31>
    <e32>b</e32>
    <e33>c</e33>
  </E2>
  <test>a</test>
  <E2>
    <e31>u</e31>
    <e32>v</e32>
    <e33>w</e33>
  </E2>
  <E2>
    <e31>x</e31>
    <e32>y</e32>
    <e33>z</e33>
  </E2>
</E1>

El elemento test podría convertirse teóricamente en un atributo de E1. La hoja lo intenta, pero falla: XSLT exige copiar los atributos antes que los demás nodos. Se necesitan dos pasadas. Primero, conserve los elementos convertibles y márquelos con un atributo especial. Después, convierta los marcados en atributos del padre antes de copiar los demás hijos sin cambios.

  

<< atrás

siguiente >>

 

 

 

volver arriba