I have a special case. In an xml document, I want to insert a specific element just before each child with ID. Is that possible?

I can do this without using xsl:copy of the node before which the new element is added.

XML DOCUMENT

<?xml version="1.0" encoding="UTF-8"?>
<books>
    <ul>
        <li>book name</li>
        <li>book name</li>
        <li>book name</li>
    </ul>
    <ul id='123'>
        <li>book name</li>
        <li>book name</li>
        <li>book name</li>
    </ul>
</books>

expected result

<?xml version="1.0" encoding="UTF-8"?>
<books>
    <ul>
        <li>book name</li>
        <li>book name</li>
        <li>book name</li>
    </ul>
    <anchor id="123"/>
    <ul id='123'>
        <li>book name</li>
        <li>book name</li>
        <li>book name</li>
    </ul>
</books>

Can I do this without using ? The elements with id will have separate templates. If I use xsl:copy, the element specific templates won't be applied. Your help will be much appreciated. Thanks in advance.

1 Answers

1
michael.hor257k On

The result you show can be easily achieved using:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="ul[@id]">
    <anchor id="{@id}"/>
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

If you have specific templates for processing other elements, you can add them and they will be applied.