I have an xml document
<body>
<heading>Main Heading</heading>
<para>
<text>para 1</text>
</para>
<para>
<heading>heading 2</heading>
<text> para 2</text>
</para>
<para>
<heading>heading 3</heading>
<text>para 3</text>
</para>
</body>
I want to match the first occurrence of heading element and add some text to it. I just want the first occurrence of heading and heading should be a child node of para element.
so the output should be like below
<body>
<heading>Main Heading</heading>
<para>
<text>para 1</text>
</para>
<para>
<heading>**This is a first heading found** heading 2</heading>
<text> para 2</text>
</para>
<para>
<heading>heading 3</heading>
<text>para 3</text>
</para>
</body>
This should do what you want:
para[heading][1]/heading[1]
It would match the first heading element inside the first para-that-contains-any-headings.
Example XSLT:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="@*|node()">
<xsl:copy><xsl:apply-templates select="@*|node()" /></xsl:copy>
</xsl:template>
<xsl:template match="para[heading][1]/heading[1]">
<xsl:copy>**First heading** <xsl:apply-templates select="@*|node()" /></xsl:copy>
</xsl:template>
</xsl:stylesheet>
Output on your example:
<body>
<heading>Main Heading</heading>
<para>
<text>para 1</text>
</para>
<para>
<heading>**First heading** heading 2</heading>
<text> para 2</text>
</para>
<para>
<heading>heading 3</heading>
<text>para 3</text>
</para>
</body>
If there might be <para>
elements elsewhere in the XML than just nested directly under the <body>
then you would be safer with a more specific match expression, namely
/body/para[heading][1]/heading[1]
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