Tench
Tench

Reputation: 527

XSLT 2.0: Merge sibling nodes if separated by punctuation only

Given this (simplified) XML:

<p>
    <hi rend="italic">Some text</hi>, <hi rend="italic">and some more</hi>: <hi rend="italic"
        >followed by some more.</hi>
    <hi rend="bold">This text is fully in bold.</hi> Here we have plain text, which should't be
    touched. <hi rend="bold">Here we go with bold</hi>, <hi rend="bold">yet again.</hi>
</p>

I would like to merge all the nodes that have the same name and same attribute together with all the text nodes between them but only if the normalize-space() of the text nodes can be reduced to punctuation signs.

In other words, if two or more hi[@rend='italic'] or hi[@rend='bold'] nodes are separated by text nodes containing only punctuation and spaces, they should be merged.

If, on the other hand, the text node between two hi[@rend='italic'] or two hi[@rend='bold'] nodes is not reducible to punctuation, it shouldn't be touched.

I would like to learn how to do this without hard-coding element hi and attribute @rend, i.e. I would like the stylesheet to merge any identical element/attribute combos separated by punctuation text nodes.

The punctuation characters should be matched by the regex \p{P}.

The output should look like this:

<p>
    <hi rend="italic">Some text, and some more: followed by some more.</hi>
    <hi rend="bold">This text is fully in bold.</hi> Here we have plain text, which should't be
    touched. <hi rend="bold">Here we go with bold, yet again.</hi>
</p>

Many thanks in advance.

Upvotes: 0

Views: 83

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

I am not sure there is a one step solution, one approach I could think of is a two step transformation where in a first step the inter element punctuation text nodes are transformed into elements so that the second transformation step can use group-adjacent. In the following I have used XSLT 3 and a composite grouping key composed of the element's node-name() and the sequence of node-name() sorted attribute values:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:mf="http://example.com/mf"
    exclude-result-prefixes="#all"
    version="3.0">

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:mode name="text-to-el" on-no-match="shallow-copy"/>

  <xsl:function name="mf:match" as="xs:boolean">
      <xsl:param name="e1" as="element()"/>
      <xsl:param name="e2" as="element()"/>
      <xsl:sequence
        select="deep-equal(($e1!(node-name(), mf:sort(@* except @mf:punctuation)!data())), ($e2!(node-name(), mf:sort(@* except @mf:punctuation)!data())))"/>
  </xsl:function>

  <xsl:function name="mf:sort" as="attribute()*">
      <xsl:param name="attributes" as="attribute()*"/>
      <xsl:perform-sort select="$attributes">
          <xsl:sort select="node-name()"/>
      </xsl:perform-sort>
  </xsl:function>

  <xsl:template match="text()[matches(normalize-space(.), '^\p{P}+$') and mf:match(preceding-sibling::node()[1], following-sibling::node()[1])]" mode="text-to-el">
      <xsl:element name="{node-name(preceding-sibling::node()[1])}" namespace="{namespace-uri(preceding-sibling::node()[1])}">
          <xsl:apply-templates select="preceding-sibling::node()[1]/@*" mode="#current"/>
          <xsl:attribute name="mf:punctuation">true</xsl:attribute>
          <xsl:value-of select="."/>
      </xsl:element>
  </xsl:template>

  <xsl:variable name="punctuation-text-to-element">
      <xsl:apply-templates mode="text-to-el"/>
  </xsl:variable>

  <xsl:template match="/">
      <xsl:apply-templates select="$punctuation-text-to-element/node()"/>
  </xsl:template>

  <xsl:template match="*[*]">
      <xsl:copy>
          <xsl:apply-templates select="@*"/>
          <xsl:for-each-group select="node()" composite="yes" group-adjacent="if (. instance of element()) then (node-name(), mf:sort(@* except @mf:punctuation)!data()) else false()">
              <xsl:choose>
                  <xsl:when test="current-grouping-key() instance of xs:boolean and not(current-grouping-key())">
                      <xsl:apply-templates select="current-group()"/>
                  </xsl:when>
                  <xsl:otherwise>
                      <xsl:copy>
                          <xsl:apply-templates select="@*, current-group()/node()"/>
                      </xsl:copy>
                  </xsl:otherwise>
              </xsl:choose>
          </xsl:for-each-group>
      </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/gWvjQf6

In XSLT 2 you don't have composite grouping keys but of course it is possible to string-join the sequence used in the XSLT 3 sample as a grouping key into some single string grouping key, you just have to make sure you use a separator character with string-join that doesn't occur in the element names and attribute values.

Instead of using xsl:mode the identity transformation would need to be spelled out and the use of ! has to be replaced with for .. return expressions or / steps where possible:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:mf="http://example.com/mf"
    exclude-result-prefixes="#all"
    version="2.0">

    <xsl:param name="sep" as="xs:string">|</xsl:param>

    <xsl:template match="@*|node()" mode="#all">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" mode="#current"/>
        </xsl:copy>
    </xsl:template>

  <xsl:function name="mf:match" as="xs:boolean">
      <xsl:param name="e1" as="element()"/>
      <xsl:param name="e2" as="element()"/>
      <xsl:sequence
        select="deep-equal(($e1/(node-name(.), for $att in mf:sort(@* except @mf:punctuation) return data($att))), ($e2/(node-name(.), for $att in mf:sort(@* except @mf:punctuation) return data($att))))"/>
  </xsl:function>

  <xsl:function name="mf:sort" as="attribute()*">
      <xsl:param name="attributes" as="attribute()*"/>
      <xsl:perform-sort select="$attributes">
          <xsl:sort select="node-name(.)"/>
      </xsl:perform-sort>
  </xsl:function>

  <xsl:template match="text()[matches(normalize-space(.), '^\p{P}+$') and mf:match(preceding-sibling::node()[1], following-sibling::node()[1])]" mode="text-to-el">
      <xsl:element name="{node-name(preceding-sibling::node()[1])}" namespace="{namespace-uri(preceding-sibling::node()[1])}">
          <xsl:apply-templates select="preceding-sibling::node()[1]/@*" mode="#current"/>
          <xsl:attribute name="mf:punctuation">true</xsl:attribute>
          <xsl:value-of select="."/>
      </xsl:element>
  </xsl:template>

  <xsl:variable name="punctuation-text-to-element">
      <xsl:apply-templates mode="text-to-el"/>
  </xsl:variable>

  <xsl:template match="/">
      <xsl:apply-templates select="$punctuation-text-to-element/node()"/>
  </xsl:template>

  <xsl:template match="*[*]">
      <xsl:copy>
          <xsl:apply-templates select="@*"/>
          <xsl:for-each-group select="node()" group-adjacent="if (. instance of element()) then string-join((string(node-name(.)), for $att in mf:sort(@* except @mf:punctuation) return data($att)), $sep) else false()">
              <xsl:choose>
                  <xsl:when test="current-grouping-key() instance of xs:boolean and not(current-grouping-key())">
                      <xsl:apply-templates select="current-group()"/>
                  </xsl:when>
                  <xsl:otherwise>
                      <xsl:copy>
                          <xsl:apply-templates select="@*, current-group()/node()"/>
                      </xsl:copy>
                  </xsl:otherwise>
              </xsl:choose>
          </xsl:for-each-group>
      </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

http://xsltransform.net/asnmyS

Upvotes: 3

Related Questions