Reputation: 1
Existing code snippet:
<article></article>
I want the resulting elements added (content, head, body). So that it appears like this:
<content>
<head></head>
<body>
<article></article>
</body>
<content>
Two types of inserted elements- wrapped around the e.g. and one above the element,
Here's what I've tried so far:
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="list">
<list>
<xsl:apply-templates select="@* | *"/>
<newelement>
</list>
</xsl:template>
I'm confused about template match/applying.
Upvotes: 0
Views: 387
Reputation: 180103
You are indeed confused if you supposed that the stylesheet fragment you provided would do anything resembling what you described. At least you included an identity transform -- that's usually a good start.
The match
attribute of a template element is used to associate that element with the elements of the input tree to which it should be applied. It is an XPATH expression that is evaluated potentially multiple times with various nodes as the context node. Since you want to perform a different transformation on <article>
elements than you do on most elements, you'll need a template that matches them and not the others.
Supposing you want to match a template to every <article>
element, wherever it appears in the tree, but not to any other node, that would be spelled match='article'
. Such a match is more specific than the one in your identity transform, so such a template should be chosen in preference to the identity transform for <article>
elements.
Having matched a template to the elements of interest, you need to specify the transformation it should perform. In the first place, you want to copy the <article>
element with (I presume) all its child nodes. That looks very much like the identity transform you already have. In the second place, you want to add elements around and before the <article>
; these are some of the simplest transformations you can perform, as you can express them literally.
Here, then, is one way to do the job:
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="article">
<content>
<head></head>
<body>
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</body>
</content>
</xsl:template>
</xsl:stylesheet>
Upvotes: 1