I have a piece of XML that I want to transform with XSLT (using xsltproc--so only XSLT 1.0). The original XML uses some tags as separators like this:
<container>
<element />
<element />
<separator />
<element />
<element />
<element />
<separator />
<element />
</container>
I need to transform this into a format that wraps these elements instead. So I need it to look like this:
<container>
<wrapper>
<element />
<element />
</wrapper>
<wrapper>
<element />
<element />
<element />
</wrapper>
<wrapper>
<element />
</wrapper>
</container>
I just can't seem to design a template that achieves this. Anybody out there have any thoughts?
XSLT Transformations. The Extensible Stylesheet Language Transformation (XSLT) lets you transform the content of a source XML document into another document that is different in format or structure.
Tip: To view the raw XML source, right-click in XML file and select "View Source"! View "cdcatalog.xml" Then you create an XSL Style Sheet ("cdcatalog.xsl") with a transformation template: Add the XSL style sheet reference to your XML document ("cdcatalog.xml"):
Thanks a million to Bram Ruttens aka "skeltavik" for identifying security issues in this tool and having the integrity to report them. The XSL Transformer fully supports XML namespaces, but the declarations MUST be explicit and MUST be on the root XML element of both your XML file and your XSL file. See the XSLT Examples section for details.
The Extensible Stylesheet Language Transformation (XSLT) lets you transform the content of a source XML document into another document that is different in format or structure. For example, you can use XSLT to transform XML into HTML for use on a Web site or to transform it into a document that contains only the fields required by an application.
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:key name="kFollowing" match="element"
use="generate-id(preceding-sibling::separator[1])"/>
<xsl:template match="/*">
<container>
<xsl:apply-templates select=
"element
[generate-id()
=
generate-id(key('kFollowing',
generate-id(preceding-sibling::separator[1])
)[1]
)
]"/>
</container>
</xsl:template>
<xsl:template match="element">
<wrapper>
<xsl:copy-of select=
"key('kFollowing',
generate-id(preceding-sibling::separator[1])
)"/>
</wrapper>
</xsl:template>
</xsl:stylesheet>
when applied on the provided XML document:
<container>
<element />
<element />
<separator />
<element />
<element />
<element />
<separator />
<element />
</container>
produces the wanted, correct result:
<container>
<wrapper>
<element/>
<element/>
</wrapper>
<wrapper>
<element/>
<element/>
<element/>
</wrapper>
<wrapper>
<element/>
</wrapper>
</container>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With