Tecnologías XML / XSLT / Recetario XSLT / Consultar XML / Operaciones con conjuntos de nodos según los valores

(Extracto de «XSLT Kochbuch» de Sal Mangano)

Problema

Necesita calcular unión, intersección, diferencia y diferencia simétrica de elementos de dos conjuntos, pero su problema define la igualdad de forma distinta de la identidad de los conjuntos de nodos. Es decir, la igualdad depende del valor del nodo.

Solución

XSLT 1.0

Esto cobra importancia con varios documentos. Imagine dos documentos que comparten una DTD pero no necesariamente valores de elemento duplicados. Los elementos XSLT de documentos distintos son diferentes aunque sus valores de espacio de nombres, atributos y texto coincidan, como muestran los cuatro ejemplos siguientes.

Ejemplo: people1.xslt

<people>
  <person name="Brad York" age="38" sex="m" smoker="ja"/>
  <person name="Charles Xavier" age="32" sex="m" smoker="nein"/>
  <person name="David Williams" age="33" sex="m" smoker="nein"/>
</people>

Ejemplo: people2.xslt

<people>
  <person name="Al Zehtooney" age="33" sex="m" smoker="nein"/>
  <person name="Brad York" age="38" sex="m" smoker="ja"/>
  <person name="Charles Xavier" age="32" sex="m" smoker="nein"/>
</people>

Ejemplo: intento fallido de seleccionar personas distintas con la unión XSLT.

<xsl:template match="/">
  <people>
    <xsl:copy-of select="//person | document('people2.xml')//person"/>
  </people>
</xsl:template>

Ejemplo: salida con people1.xml como entrada.

<people>
  <person name="Brad York" age="38" sex="m" smoker="ja"/>
  <person name="Charles Xavier" age="32" sex="m" smoker="nein"/>
  <person name="David Williams" age="33" sex="m" smoker="nein"/>
  <person name="Al Zehtooney" age="33" sex="m" smoker="nein"/>
  <person name="Brad York" age="38" sex="m" smoker="ja"/>
  <person name="Charles Xavier" age="32" sex="m" smoker="nein"/>
</people>

Incluso un documento plantea problemas si la identidad de nodos debe depender de sus valores de texto y atributos.

Esta hoja proporciona una implementación reutilizable de unión, intersección y diferencia según los valores. Una hoja importadora sobrescribe la plantilla cuyo mode="vset:element-equality" está definido, para establecer la igualdad apropiada a su entrada:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:vset="http:/www.ora.com/XSLTCookbook/namespaces/vset">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
  <!-- Die vorgegebene Implementierung der Elementgleichheit. Wenn notwendig, im importierenden Stylesheet außer Kraft setzen. -->
  <xsl:template match="node( ) | @*" mode="vset:element-equality">
    <xsl:param name="other"/>
    <xsl:if test=". = $other">
      <xsl:value-of select="true( )"/>
    </xsl:if>
  </xsl:template>
  <!-- Der vorgegebene Mengenmitgliedschaftstest verwendet Elementgleichheit. Sie müssen dies im importierenden Stylesheet selten außer Kraft setzen. -->
  <xsl:template match="node( ) | @*" mode="vset:member-of">
    <xsl:param name="elem"/>
    <xsl:variable name="member-of">
      <xsl:for-each select=".">
        <xsl:apply-templates select="." mode="vset:element-equality">
          <xsl:with-param name="other" select="$elem"/>
        </xsl:apply-templates>
      </xsl:for-each>
    </xsl:variable>
    <xsl:value-of select="string($member-of)"/>
  </xsl:template>
  <!-- Berechnen der Vereinigung zweier Mengen mittels Gleichheit "nach Wert". -->
  <xsl:template name="vset:union">
    <xsl:param name="nodes1" select="/.." />
    <xsl:param name="nodes2" select="/.." />
    <!-- für die interne Benutzung -->
    <xsl:param name="nodes" select="$nodes1 | $nodes2" />
    <xsl:param name="union" select="/.." />
    <xsl:choose>
      <xsl:when test="$nodes">
        <xsl:variable name="test">
          <xsl:apply-templates select="$union" mode="vset:member-of">
            <xsl:with-param name="elem" select="$nodes[1]" />
          </xsl:apply-templates>
        </xsl:variable>
        <xsl:call-template name="vset:union">
          <xsl:with-param name="nodes" select="$nodes[position( ) &gt; 1]" />
          <xsl:with-param name="union" select="$union | $nodes[1][not(string($test))]" />
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <xsl:apply-templates select="$union" mode="vset:union" />
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
  <!-- Standardmäßiges Zurückliefern einer Kopie der Vereinigung. Im importierenden Stylesheet überschreiben, um Ergebnisse als "Callback" zu empfangen-->
  <xsl:template match="/ | node( ) | @*" mode="vset:union">
   <xsl:copy-of select="."/>
  </xsl:template>
  <!-- Berechnen des Durchschnitts zweier Mengen mittels Gleichheit "nach Wert". -->
  <xsl:template name="vset:intersection">
    <xsl:param name="nodes1" select="/.."/>
    <xsl:param name="nodes2" select="/.."/>
    <!-- für die interne Benutzung -->
    <xsl:param name="intersect" select="/.."/>
    <xsl:choose>
      <xsl:when test="not($nodes1)">
        <xsl:apply-templates select="$intersect" mode="vset:intersection"/>
      </xsl:when>
      <xsl:when test="not($nodes2)">
        <xsl:apply-templates select="$intersect" mode="vset:intersection"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:variable name="test1">
          <xsl:apply-templates select="$nodes2" mode="vset:member-of">
            <xsl:with-param name="elem" select="$nodes1[1]"/>
          </xsl:apply-templates>
        </xsl:variable>
        <xsl:variable name="test2">
          <xsl:apply-templates select="$intersect" mode="vset:member-of">
            <xsl:with-param name="elem" select="$nodes1[1]"/>
          </xsl:apply-templates>
        </xsl:variable>
        <xsl:choose>
          <xsl:when test="string($test1) and not(string($test2))">
            <xsl:call-template name="vset:intersection">
              <xsl:with-param name="nodes1" select="$nodes1[position( ) &gt; 1]"/>
              <xsl:with-param name="nodes2" select="$nodes2"/>
              <xsl:with-param name="intersect" select="$intersect | $nodes1[1]"/>
            </xsl:call-template>
          </xsl:when>
          <xsl:otherwise>
            <xsl:call-template name="vset:intersection">
              <xsl:with-param name="nodes1" select="$nodes1[position( ) &gt; 1]"/>
              <xsl:with-param name="nodes2" select="$nodes2"/>
              <xsl:with-param name="intersect" select="$intersect"/>
            </xsl:call-template>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
  <!-- Standardmäßiges Zurückliefern einer Kopie des Durchschnitts. Im importierenden Stylesheet überschreiben, um Ergebnisse als "Callback" zu empfangen-->
  <xsl:template match="/ | node( ) | @*" mode="vset:intersection">
    <xsl:copy-of select="."/>
  </xsl:template>
  <!-- Berechnen der Differenz zweier Mengen (nodes1 - nodes2) mittels Gleichheit "nach Wert". -->
  <xsl:template name="vset:difference">
    <xsl:param name="nodes1" select="/.."/>
    <xsl:param name="nodes2" select="/.."/>
    <!-- für die interne Benutzung -->
    <xsl:param name="difference" select="/.."/>
    <xsl:choose>
      <xsl:when test="not($nodes1)">
        <xsl:apply-templates select="$difference" mode="vset:difference"/>
      </xsl:when>
      <xsl:when test="not($nodes2)">
        <xsl:apply-templates select="$nodes1" mode="vset:difference"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:variable name="test1">
          <xsl:apply-templates select="$nodes2" mode="vset:member-of">
            <xsl:with-param name="elem" select="$nodes1[1]"/>
          </xsl:apply-templates>
        </xsl:variable>
        <xsl:variable name="test2">
          <xsl:apply-templates select="$difference" mode="vset:member-of">
            <xsl:with-param name="elem" select="$nodes1[1]"/>
          </xsl:apply-templates>
        </xsl:variable>
        <xsl:choose>
          <xsl:when test="string($test1) or string($test2)">
            <xsl:call-template name="vset:difference">
              <xsl:with-param name="nodes1" select="$nodes1[position( ) &gt; 1]"/>
              <xsl:with-param name="nodes2" select="$nodes2"/>
              <xsl:with-param name="difference" select="$difference"/>
            </xsl:call-template>
          </xsl:when>
          <xsl:otherwise>
            <xsl:call-template name="vset:difference">
              <xsl:with-param name="nodes1" select="$nodes1[position( ) &gt; 1]"/>
              <xsl:with-param name="nodes2" select="$nodes2"/>
              <xsl:with-param name="difference" select="$difference | $nodes1[1]"/>
            </xsl:call-template>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
  <!-- Standardmäßiges Zurückliefern einer Kopie der Differenz. Im importierenden Stylesheet überschreiben, um die Ergebnisse als "Callback" zu empfangen-->
  <xsl:template match="/ | node( ) | @*" mode="vset:difference">
    <xsl:copy-of select="."/>
  </xsl:template>
</xsl:stylesheet>

Estas plantillas recursivas implementan las definiciones siguientes:

Vereinigung(knoten1,knoten2)

La unión contiene todo lo que está en knoten2 y todo lo que está en knoten1 sin pertenecer ya a knoten2.

Durchschnitt(knoten1,knoten2)

La intersección contiene todo lo que está en knoten1 y también pertenece a knoten2.

Differenz(knoten1,knoten2)

La diferencia contiene todo lo que está en knoten1 sin pertenecer a knoten2.

La pertenencia se basa por defecto en la igualdad de valores de cadena, pero la hoja importadora puede redefinirla.

Con estas operaciones basadas en valores, la hoja siguiente produce el efecto deseado para people1.xml y people2.xml:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:vset="http:/www.ora.com/XSLTCookbook/namespaces/vset">
  <xsl:import href="set.ops.xslt"/>
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
  <xsl:template match="/">
    <people>
      <xsl:call-template name="vset:union">
        <xsl:with-param name="nodes1" select="//person"/>
        <xsl:with-param name="nodes2" select="document('people2.xml')//person"/>
      </xsl:call-template>
    </people>
  </xsl:template>
  <!--Personengleichheit wird so definiert, dass der gleiche Name vorliegen muss -->
  <xsl:template match="person" mode="vset:element-equality">
    <xsl:param name="other"/>
    <xsl:if test="@name = $other/@name">
      <xsl:value-of select="true( )"/>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

XSLT 2.0

La principal mejora de XSLT 2.0 aprovecha funciones de primera clase y secuencias, eliminando la recursión y el truco de devolución de llamada y aclarando definiciones y uso. Las funciones vset:element-equality y vset:member-of pueden seguir sobrescribiéndose en hojas importadoras para adaptar su comportamiento.

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vset="http:/www.ora.com/XSLTCookbook/namespaces/vset">
  <!-- Die vorgegebene Implementierung der Elementgleichheit. Wenn notwendig, im importierenden Stylesheet außer Kraft setzen. -->
  <xsl:function name="vset:element-equality" as="xs:boolean">
    <xsl:param name="item1" as="item( )?"/>
    <xsl:param name="item2" as="item( )?"/>
    <xsl:sequence select="$item1 = $item2"/>
  </xsl:function>
  <!-- Der vorgegebene Mengenmitgliedschaftstest verwendet Elementgleichheit. Dies müssen Sie im importierenden Stylesheet selten überschreiben. -->
  <xsl:function name="vset:member-of" as="xs:boolean">
    <xsl:param name="set" as="item( )*"/>
    <xsl:param name="elem" as="item( )"/>
    <xsl:variable name="member-of" as="xs:boolean*" select="for $test in $set return if (vset:element-equality($test, $elem)) then true( ) else ( )"/>
    <xsl:sequence select="not(empty($member-of))"/>
  </xsl:function>
  <!-- Berechnen der Vereinigung zweier Mengen mittels Gleichheit "nach Wert". -->
  <xsl:function name="vset:union" as="item( )*">
    <xsl:param name="nodes1" as="item( )*"  />
    <xsl:param name="nodes2" as="item( )*" />
    <xsl:sequence select="$nodes1, for $test in $nodes2 return if (vset:member-of($nodes1,$test)) then ( ) else $test"/>
  </xsl:function>
  <!-- Berechnen des Durchschnitts zweier Mengen mittels Gleichheit "nach Wert". -->
  <xsl:function name="vset:intersection" as="item( )*">
    <xsl:param name="nodes1" as="item( )*" />
    <xsl:param name="nodes2" as="item( )*" />
    <xsl:sequence select="for $test in $nodes1 return if (vset:member-of($nodes2,$test)) then $test else ( )"/>
  </xsl:function>
  <!-- Berechnen der Differenz zweier Mengen (nodes1 - nodes2) mittels Gleichheit "nach Wert". -->
  <xsl:function name="vset:difference" as="item( )*">
    <xsl:param name="nodes1" as="item( )*" />
    <xsl:param name="nodes2" as="item( )*" />
    <xsl:sequence select="for $test in $nodes1 return if (vset:member-of($nodes2,$test)) then ( ) else $test"/>
  </xsl:function>
</xsl:stylesheet>

Discusión

La igualdad parece trivial: las cosas son iguales o no. En programación, como en política, depende del observador. Un documento suele asociar un elemento con un objeto identificable. Un párrafo, <p>...</p>, difiere de otro aunque tengan idéntico contenido. Por ello las operaciones suelen utilizar la identidad única de elementos. Con varios documentos o elementos resultantes de xsl:copy, defina cuidadosamente la igualdad deseada.

Estas consultas requieren semántica basada en valores:

  1. Dos documentos utilizan espacios de nombres distintos. Los cuatro ejemplos siguientes encuentran nombres locales de elementos comunes y exclusivos de cada espacio de nombres.

Ejemplo: doc1.xml

<doc xmlns:doc1="doc1" xmlns="doc1">
  <chapter label="1">
    <section label="1">
      <p>Es war einmal...</p>
    </section>
  </chapter>
  <chapter label="2">
    <note to="editor">Ich warte immer noch auf meinen Vorschuss von $100000.</note>
    <section label="1">
      <p>... und sie lebten glücklich bis an ihr Ende.</p>
    </section>
  </chapter>
</doc>

Ejemplo: doc2.xml

<doc xmlns:doc1="doc2" xmlns="doc2">
  <chapter label="1">
    <section label="1">
      <sub>
        <p>Es war einmal... <ref type="footnote" label="1"/></p>
      </sub>
      <fig>Figure1</fig>
    </section>
    <footnote label="1">Hey schubidubi.</footnote>
  </chapter>
  <chapter label="2">
    <section label="1">
      <p>... und sie lebten glücklich bis an ihr Ende.</p>
    </section>
  </chapter>
</doc>

Ejemplo: unique-element-names.xslt

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:doc1="doc1" xmlns:doc2="doc2" xmlns:vset="http:/www.ora.com/XSLTCookbook/namespaces/vset" extension-element-prefixes="vset">
  <xsl:import href="set.ops.xslt"/>
  <xsl:output method="text" />
  <xsl:template match="/">
    <xsl:text>&#xa;Gemeinsame Elemente sind: </xsl:text>
    <xsl:call-template name="vset:intersection">
      <xsl:with-param name="nodes1" select="//*"/>
      <xsl:with-param name="nodes2" select="document('doc2.xml')//*"/>
    </xsl:call-template>
    <xsl:text>&#xa;Elemente nur in doc1 sind: </xsl:text>
    <xsl:call-template name="vset:difference">
      <xsl:with-param name="nodes1" select="//*"/>
      <xsl:with-param name="nodes2" select="document('doc2.xml')//*"/>
    </xsl:call-template>
    <xsl:text>&#xa;Elemente nur in doc2 sind: </xsl:text>
    <xsl:call-template name="vset:difference">
      <xsl:with-param name="nodes1" select="document('doc2.xml')//*"/>
      <xsl:with-param name="nodes2" select="//*"/>
    </xsl:call-template>
    <xsl:text>&#xa;</xsl:text>
  </xsl:template>
  <xsl:template match="*" mode="vset:intersection">
    <xsl:value-of select="local-name(.)"/>
    <xsl:if test="position() != last()">
      <xsl:text>, </xsl:text>
    </xsl:if>
  </xsl:template>
  <xsl:template match="*" mode="vset:difference">
    <xsl:value-of select="local-name(.)"/>
    <xsl:if test="position() != last()">
      <xsl:text>, </xsl:text>
    </xsl:if>
  </xsl:template>
  <xsl:template match="doc1:* | doc2:*" mode="vset:element-equality">
    <xsl:param name="other"/>
    <xsl:if test="local-name(.) = local-name($other)">
      <xsl:value-of select="true()"/>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

Ejemplo: salida.

Gemeinsame Elemente sind: doc, chapter, section, p Elemente nur in doc1 sind: note Elemente nur in doc2 sind: sub, ref, fig, footnote

  1. Un documento XML Visio contiene formas maestras, sus instancias y formas personalizadas sin maestra. Quiere extraer los datos de las formas distintas. Dos formas son iguales para esta consulta si se cumple una condición:

    • Ambas tienen atributos de maestra, @Master, con valores iguales.

    • Al menos una carece del atributo de maestra, pero sus elementos geométricos, Geom, son iguales. Los elementos geométricos son iguales si todos los atributos de todos los descendientes de Geom son iguales.

    De lo contrario son distintas.

    Impleméntelo intersectando todas las formas consigo mismas según esas reglas de igualdad.

    Nota:
    Matemáticamente, la intersección de un conjunto consigo mismo no cambia. Eso es cierto para conjuntos sin duplicados. Aquí la igualdad depende de la aplicación y los conjuntos de nodos no suelen ser conjuntos verdaderos según esa prueba. Las operaciones sobre valores siempre producen conjuntos verdaderos, por lo que esta técnica elimina duplicados.

    También puede utilizar la plantilla vset:union con el parámetro nodes:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:vxd="urn:schemas-microsoft-com:office:visio" xmlns:vset="http:/www.ora.com/XSLTCookbook/namespaces/vset" extension-element-prefixes="vset">
  <xsl:import href="set.ops.xslt"/>
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
  <xsl:template match="/">
    <UniqueShapes>
      <xsl:call-template name="vset:intersection">
        <xsl:with-param name="nodes1" select="//vxd:Pages/*/*/vxd:Shape"/>
        <xsl:with-param name="nodes2" select="//vxd:Pages/*/*/vxd:Shape"/>
      </xsl:call-template>
    </UniqueShapes>
  </xsl:template>
  <xsl:template match="vxd:Shape" mode="vset:intersection">
    <xsl:copy-of select="." />
  </xsl:template>
  <xsl:template match="vxd:Shape" mode="vset:element-equality">
    <xsl:param name="other"/>
    <xsl:choose>
      <xsl:when test="@Master and $other/@Master and @Master = $other/@Master">
        <xsl:value-of select="true( )"/>
      </xsl:when>
      <xsl:when test="not(@Master) or not($other/@Master)">
        <xsl:variable name="geom1">
          <xsl:for-each select="vxd:Geom//*/@*">
            <xsl:sort select="name( )"/>
            <xsl:value-of select="."/>
          </xsl:for-each>
        </xsl:variable>
        <xsl:variable name="geom2">
          <xsl:for-each select="$other/vxd:Geom//*/@*">
            <xsl:sort select="name( )"/>
            <xsl:value-of select="."/>
          </xsl:for-each>
        </xsl:variable>
        <xsl:if test="$geom1 = $geom2">
          <xsl:value-of select="true( )"/>
        </xsl:if>
      </xsl:when>
    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>

  

<< atrás

siguiente >>

 

 

 

volver arriba