Reputation: 21
I'm new in xsl and need help :(. I need to get child node as value of parent note.
<planet>
<venus> sometext
<mass>123</mass>
</venus>
<mars>text about mars</mars>
</planet>
So I have to get it in this form:
<venus>sometext
<mass>123</mass>
</venus>
<mars> text about mars <mars>
Nodes have to be within signs "<" and ">" as compile thinks they are content of parent note. Thanks!!!
Upvotes: 2
Views: 6897
Reputation: 243599
This transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="planet">
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>
when applied on the provided XML document:
<planet>
<venus> sometext
<mass>123</mass>
</venus>
<mars>text about mars</mars>
</planet>
produces the wanted, correct result:
<venus> sometext
<mass>123</mass>
</venus>
<mars>text about mars</mars>
A second solution -- more direct and shorter:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/*">
<xsl:copy-of select="node()"/>
</xsl:template>
</xsl:stylesheet>
Explanation:
In both solutions we avoid copying of the root of the element tree, and copy its subtree.
In the first solution the copying of the subtree is the effect of the identity rule -- this gives us more flexibility if in the future we change our plans and decide not simply to copy the nodes of the subtree but to transform some or all of them.
In the second solution the copying is done with a single XSLT instruction -- <xsl:copy-of>
. Here we trade flexibility for speed and compactness.
Upvotes: 2
Reputation: 12154
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:for-each select="*">
<xsl:apply-templates select="@*|node()"/>
</xsl:for-each>
</xsl:template>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Upvotes: 2