2

I'm trying to insert some HTML at a given point. The XML file has a content node, which inside that has actual HTML. For exmaple here is the content section of the XML:

-----------------
<content>
    <h2>Header</h2>
    <p><a href="...">some link</a></p>
    <p><a href="...">some link1</a></p>
    <p><a href="...">some link2</a></p>
</content>
-----------------

I need to insert a link after the header but before the first link, inside its own p tag. A little rusty with XSLT, any help is appreciated!

2 Answers 2

3

Given this source:

<html>
    <head/>
    <body>
        <content>
            <h2>Header</h2>
            <p><a href="...">some link</a></p>
            <p><a href="...">some link1</a></p>
            <p><a href="...">some link2</a></p>
        </content>
    </body>
</html>

This stylesheet will do what you want to do:

<?xml version="1.0" encoding="utf-8"?>
<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="/html/body/content/h2">
        <xsl:copy>
            <xsl:apply-templates/>
        </xsl:copy>
        <p><a href="...">your new link</a></p>
    </xsl:template>
</xsl:stylesheet>
Sign up to request clarification or add additional context in comments.

1 Comment

Both helped but it was nice to see the entire thing put together like this helped me understand more. Good answer thank you!
3
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="/content">
        <xsl:copy-of select="h2"/>
        <a href="">foo</a>
        <xsl:copy-of select="p"/>
    </xsl:template>
</xsl:stylesheet>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.