output node with subnodes "as-is"

  • Thread starter Kristofer Andersson
  • Start date
K

Kristofer Andersson

I am using xslt to transform some parts of a document but want to
output some parts of the document just like they are (node with all
subnodes and attributes).

Below are the templates I am currently using. The only problem I have
is that the value of parent nodes will be the value of all subnodes ie
"<parentnode><childnode>value</childnode></parentnode>" will become
"<parentnode>value<childnode>value</childnode></parentnode>" after
transformation. Can I avoid this? Or can this be done in a more simple
way than the somewhat clumsy templates below?

<xsl:template match="mySubtree">
<xsl:element name="subtreeWrapperNode">
<xsl:apply-templates mode="subNodes" select="." />
</xsl:element>
</xsl:template>

<xsl:template mode="subNodes" match="*">
<xsl:for-each select="*">
<xsl:element name="{name()}">
<xsl:for-each select="@*">
<xsl:attribute name="{name()}"><xsl:value-of select="."
/></xsl:attribute>
</xsl:for-each>
<xsl:value-of select="." />
<xsl:apply-templates mode="subNodes" select="." />
</xsl:element>
</xsl:for-each>
</xsl:template>
 
D

David Carlisle

as another respondentsaid, if you just want the whole subtree
unchanged then you can just do

<xsl:template match="mySubtree">
<xsl:copy-of select="."/>
</xsl:template>

and need nothing else. A more usual case is where you want templates
that do an identity transform but then have higher priority templates
for certain special attributes that do something other than copy.
even there your code is very verbose

<xsl:element name="{name()}">

you can use
<xsl:copy>

for that
<xsl:for-each select="@*">
<xsl:attribute name="{name()}"><xsl:value-of select="."
/></xsl:attribute>

that's

<xsl:copt-of select="@*"/>

<xsl:value-of select="." />
<xsl:apply-templates mode="subNodes" select="."
/>

That would mangle your input
the value-of gives the string value of the current node, which is all
the character content of all the descendants then you process all the
child elements again (so you'll get much of teh content again in a
typical case)

The XSLT spec has an example identity transform.

David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top