tags:

views:

117

answers:

3

I'm having problems understanding xslt. In my source document I have to find the inner text from a <p> tag with the class attribute that is equal to "deck".

In my source xml somewhere:

<body>
   <p class="deck">Text here</p>
... ... cut ... ... ...

In my xsl file

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:TimeInc="http://www.timeinc.com/namespaces/PAMTimeInc/1.0/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:prism="http://prismstandard.org/namespaces/basic/2.1/"
    xmlns:pam="http://prismstandard.org/namespaces/pam/2.1/"
    xmlns:pim="http://prismstandard.org/namespaces/pim/2.1/"
    xmlns:prl="http://prismstandard.org/namespaces/prl/2.1/"&gt;

    <xsl:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="yes"/>
    <Description>
     <xsl:choose>
       <xsl:when test="//p@deck != ''">
        <xsl:value-of select="//p@deck"/>
       </xsl:when>
       <xsl:otherwise>
        <xsl:text disable-output-escaping="yes"/>
       </xsl:otherwise>
     </xsl:choose>
    </Description>
... ... cut ... ... ...

It is obviously incorrect because I do not know what I'm doing. Is there an example somewhere as to how to do this or understand it more.

+2  A: 

You can express a conditional match on an element based on an attribute value with, for example

element[@attribute = 'hello']

For your specific case:

<p class="deck">Text here</p>

Try:

//p[@class = 'deck']/text()

Which is an XPath expression and can be read as returning a sequence of the text content of all p elements with an attribute class whose value is 'deck'.

XSLT uses XPath to navigate XML documents, so it might be worth reading up on XPath as well as XSLT.

Brabster
I'm reading up w3schools right now, but am having difficulty understanding the language and concepts. their "try it" section is allowing me to gain understanding though, by making changes and seeing what the change does. I'm reading up on XPath as well.
stephenbayer
+1  A: 

I don't see an anywhwhere to serve as the base of your template. I'm assuming this is a cut and paste problem, though.

Anyway, an xpath to find all p elements with class attribute set to deck is: //p[@class='deck']

You could iterate through them with:

<xsl:for-each select="//p[@class='deck'">
</xsl:for-each>
jsight
thank you very much, the final code ended up being: <Description> <xsl:for-each select="//p[@class='deck']" > <xsl:copy > <xsl:apply-templates/> </xsl:copy> </xsl:for-each> </Description>
stephenbayer
+1  A: 

Hmm... Something like this perhaps:

<Description>
    <xsl:choose>
        <xsl:when test="//p[@class='deck']">
            <xsl:value-of select="//p[@class='deck']" />
        </xsl:when>
        <xsl:otherwise>
            <xsl:test> </xsl:text>
        </xsl:otherwise>
    </xsl:choose>
</Description>
LorenVS