Search code examples
htmlxmlurlxslthref

how to get the url running in xml using xsl?


FoI have something like this in my xml file

    <tutor>
        <heading>tutor</heading>
        <p>paragraph</p>
        <p>paragraph one two <a href="http://three.com">three</a> four give</p>
        <ul>
            <li>item</li>
            <li>item</li>
            <li>item</li>
        </ul>
        <p>paragraph</p>
        <p>paragraph<a href="http://acho.com">test</a> one two two three</p>
        <p>paragraph</p>
        <p>paragraph</p>
    </tutor>

how can I output the links correctly using xsl? I tried applying templates and using for-each but just couldn't do it correctly I have something like this in my xsl file

  <xsl:template match="tutor">
    <h4><xsl:value-of select="./heading" /></h4>
    <p><xsl:value-of select="./p" /></p>
    <a href="{./p/a/@href}"><xsl:value-of select="./p/a" /></a>
  </xsl:template>

but and something similar but just couldn't get it right. Can someone please give me a hand? Thanks

my output that I want is something like....

tutor
paragraph
paragraph one two three four give
the bullet lists and so on

and where three is will be a link just like how things are outputted in html


Solution

  • The problem with your current statement...

    ... is that this is only going to look for an a element in the first p element in the XML, which is not the case here.

    If your XML already contains valid HTML elements, you can just use the XSLT Identity Template to output them as they appear

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

    Then, you only need to write templates for the XML elements you do wish to change. For example, you don't want to output the tutor elements, so you can add a template to skip over it

    <xsl:template match="tutor">
        <xsl:apply-templates/>
    </xsl:template>
    

    And to change heading into h4 you write a template like this

    <xsl:template match="heading">
        <h4><xsl:apply-templates/></h4>
    </xsl:template>
    

    All other elements p and a and ul will be output as they are.

    Try this XSLT

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
        <xsl:output method="html" indent="yes" />
    
        <xsl:template match="tutor">
            <xsl:apply-templates/>
        </xsl:template>
    
        <xsl:template match="heading">
            <h4><xsl:apply-templates/></h4>
        </xsl:template>
    
        <xsl:template match="@*|node()">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:template>
    </xsl:stylesheet>