XML technologies / XSLT / XSLT Cookbook / Querying XML / Node-set operations using value semantics

(Excerpt from “XSLT Kochbuch” by Sal Mangano)

Problem

You need union, intersection, difference and symmetric difference of elements in two node sets, but your problem defines equality differently from node-set identity. In other words, equality depends on a node’s value.

Solution

XSLT 1.0

This becomes important when working with several documents. Imagine two documents sharing a DTD but not necessarily duplicate element values. XSLT elements from different documents are distinct even when their namespace, attribute and text values match, as the following four examples show.

Example: 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>

Example: 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>

Example: Failed attempt to select distinct people with XSLT union.

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

Example: Output with people1.xml as input.

<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>

Even one document causes problems if node identity is meant to depend on text and attribute values.

This stylesheet provides reusable union, intersection and difference with value semantics. An importing stylesheet overrides the template whose mode="vset:element-equality" is set, defining the equality appropriate to its input:

<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>

These recursive templates implement the following definitions:

Vereinigung(knoten1,knoten2)

Union contains everything in knoten2 and everything in knoten1 not already in knoten2.

Durchschnitt(knoten1,knoten2)

Intersection contains everything in knoten1 that also belongs to knoten2.

Differenz(knoten1,knoten2)

Difference contains everything in knoten1 not belonging to knoten2.

Membership defaults to string-value equality in every case, but importing stylesheets can override this.

With these value-based operations, the following stylesheet gives the intended effect for people1.xml and 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

The main improvement in XSLT 2.0 exploits first-class functions and sequences, eliminating recursion and the callback trick while clarifying definitions and use. Functions vset:element-equality and vset:member-of can still be overridden in importing stylesheets to customise behaviour.

<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>

Discussion

Equality may seem trivial: things are equal or not. In programming, as in politics, it depends on the observer. A typical document associates an element with a uniquely identifiable object. A paragraph, <p>...</p>, differs from another elsewhere even with identical content. Set operations therefore normally use unique element identity. For multiple documents, or elements resulting from xsl:copy, carefully define the intended equality.

Here are queries requiring value-set semantics:

  1. Two documents use different namespaces. The next four examples find their shared local element names and those unique to either namespace.

Example: 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>

Example: 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>

Example: 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>

Example: Output.

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

  1. A Visio XML document contains master shapes, their instances and custom shapes without masters. You want data for all distinct shapes. For this query, two shapes are equal if either condition holds:

    • Both have master attributes, @Master, with equal values.

    • At least one lacks a master attribute, but their geometry elements, Geom, are equal. Geometry elements are equal when all attributes of all descendants of Geom are equal.

    Otherwise, they are unequal.

    Implement this by intersecting all shapes with themselves using those equality rules.

    Note:
    Mathematically, a set intersected with itself is unchanged. That is true for genuine sets without duplicates. Here, however, equality is application-specific, and node sets are typically not genuine sets under that test. Value-set operations always produce genuine sets, so this technique removes duplicates.

    You can also use template vset:union with parameter 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>

  

 

 

 

back to top