XSLT: How to convert XML Node to String

Viewed 50241
<ROOT>
   <A>
      <B>TESTING</B>
   </A>
</ROOT>

XSL:

<xsl:variable name="nodestring" select="//A"/>
<xsl:value-of select="$nodestring"/>

I am trying to convert XML nodeset to string using XSL. Any thoughts?

11 Answers

All solutions miss text after node and attributes in single quotes. Example

<b f1='"' f2="'">one</b>
,
<b>two</b>

My solution based on @Ilya-Kharlamov

<xsl:template name="f_serialize_node_to_string" xmlns:exsl="http://exslt.org/common" extension-element-prefixes="exsl">
    <xsl:param name="node"/>

    <xsl:variable name="node_" select="exsl:node-set($node)"/>

    <xsl:variable name="name" select="name($node_)"/>
    <xsl:variable name="q">'</xsl:variable>
    <xsl:variable name="qq">"</xsl:variable>

    <xsl:if test="$name">
        <xsl:value-of select="concat('&lt;',$name)"/>
        <xsl:for-each select="$node_/@*">
            <xsl:choose>
              <xsl:when test="contains(., $qq)">
                    <xsl:value-of select="concat(' ',name(),'=',$q,.,$q,' ')"/>
                </xsl:when>
              <xsl:otherwise>
                    <xsl:value-of select="concat(' ',name(),'=&quot;',.,'&quot; ')"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each>
        <xsl:value-of select="concat('&gt;', ./text())"/>
    </xsl:if>
    <xsl:for-each select="$node_/*">
        <xsl:call-template name="f_serialize_node_to_string">
            <xsl:with-param name="node" select="."/>
        </xsl:call-template>
    </xsl:for-each>
    <xsl:if test="$name">
        <xsl:value-of select="concat('&lt;/',$name,'&gt;')"/>
    </xsl:if>
    <xsl:if test="$node_/following-sibling::text()">
        <xsl:value-of select="$node_/following-sibling::text()" />
    </xsl:if>
</xsl:template>
Related