Given XML like:
<a>
<b>
<c>some keyword</c>
</b>
</a>
I need to add new node to the parent node of a in case if node c contains text “keyword”, so it will look like
<a>
<b>
<c>some keyword</c>
</b>
</a>
<x> new node X </x>
I can match the text with expression:
<xsl:template match="//a/b/c[matches(text(),'\.*keyword\.*')]">
<xsl:copy-of select="."/>
<xsl:element name="x">
<xsl:text> new node </xsl:text>
</xsl:element>
</xsl:template>
and this results in
<a>
<b>
<c>some keyword</c>
<x> new node X </x>
</b>
</a>
How can I fix that?
You have to add the
xelement while matchinga‘s parent. You can refer to any child element or attribute inside a predicate. What I mean is that you have to take a peek at what’s inside a’s parent while copying it. Doing it while copying the a, b or c element is just too late.The following stylesheet should do the trick. I don’t have any XSLT2.0 capable processor on me right now so I can’t check it but you should be able to see the logic in it.