Dono
Dono

Reputation: 53

XML convert Node into String using XSLT 2.0

I've searched for renaming an XML node to a string. I have found examples of strings within XML to Nodes but not the other way.

Is it possible to do the following

<par>
<run> Some text <break/> </run>
</par>

<par>
<run> some text with no carraige return</run>
</par>

To:

<par>
<run> Some text &#10; </run>
</par>

Many thanks in advance for any replies.

Dono

Upvotes: 0

Views: 914

Answers (1)

Thomas W
Thomas W

Reputation: 15361

Certainly that's possible. Just use an identity transform and handle <break> specially. Instead of copying it using <xsl:copy>, output any text you like:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="2.0">

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

  <xsl:template match="break">
    <xsl:value-of select="'&#10;'"/>
  </xsl:template>

</xsl:stylesheet>

I you want the literal output &#10; you can use disable-output-escaping, like

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="2.0">

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

  <xsl:template match="break">
    <xsl:value-of select="'&amp;#10;'" disable-output-escaping="yes"/>
  </xsl:template>

</xsl:stylesheet>

However, this is an optional feature and not guaranteed to be supported by any XSLT processor.

Upvotes: 1

Related Questions