Search code examples
xmlxsltattributestransfer

Tranfer attribute into a new element


First of all I hope I will be understood.

I have this:

       <item>
             <ptr target="X"/>BlahBlah
       </item>

And I would like to convert it into this:

    <li>
        <a href="X">Blahblah</a>
    </li>

All I could do was create this:

<xsl:template match="tei:ptr">
        <li>
            <a>
                <xsl:value-of select="parent::node()"/>
            </a>
        </li>
        <xsl:apply-templates/>
    </xsl:template>

But the result wasn't the one I was waiting for:

<li>
      <a>BlahBlah</a>
</li>BlahBlah

I could change the elements I wanted but the content of the <item> element was displayed twice, and I ignore the way to display the href attribute. If required I can show my entire XSL sheet.

I searched through the stackoverflow without result, maybe I just don't know how to put my problem into words.

Could someone help and explain how it does work? I know I have little understanding of XSLT, but I'm trying.

Thank you very much for your answer,

Matthias


Solution

  • One way to achieve this is:

    <xsl:template match="//item/text()">
        <xsl:if test="normalize-space(.) != ''">
            <li>
                <xsl:element name="a">
                    <xsl:attribute name="href">
                        <xsl:value-of select="../ptr/@target" />
                    </xsl:attribute>
                    <xsl:value-of select="normalize-space(.)" />
                </xsl:element>
            </li>
        </xsl:if>
    </xsl:template>
    

    which results in

    <?xml version="1.0" encoding="UTF-8"?>
    <li>
        <a href="X">BlahBlah</a>
    </li>
    

    You might replace the //item with a relative path to the item element if appropriate.