Reputation: 11
My aim is to use my xml (version 1.0) and xsl (version 1.0) files to create html pages.
This is the code in my XML file:
<Photo>
<Text id="one">This is the first Photo</Text>
<Image id="one" src="http://cdn.theatlantic.com/static/infocus/ngpc112812/s_n01_nursingm.jpg" /> </Photo>
<Photo>
<Text id="run">This is the run picture/Text>
<Image id="run" src="http://www.krav-maga.org.uk/uploads/images/news/running.jpg" /> </Photo>
I am trying to select individual pieces of my XML document by using their ID. I would also do this with other text or paragraphs which' I will give an ID, too. At the moment I am using a for-each function to present all images at once, but I don' know how I exactly I could select individual files. I was thinking about something like this:
<xsl:value-of select="Photo/Text[one]"/>
<img>
<xsl:attribute name="src" id="one">
<xsl:value-of select="Photo/Image/@src"/>
</xsl:attribute>
</img>
and
<xsl:value-of select="Photo/Text[run]"/>
<img>
<xsl:attribute name="src" id="run">
<xsl:value-of select="Photo/Image/@src"/>
</xsl:attribute>
</img>
But it doesn't work:( I tried what I can but I am lost. Could you help me?
Upvotes: 1
Views: 625
Reputation: 70598
The syntax you are looking for is this
<xsl:value-of select="Photo/Text[@id='one']" />
And this
<xsl:value-of select="Photo/Image[@id='one']/@src" />
However, you probably don't want to repeat this coding for every single possible @id you may have. It would be easy to use template matching here, and simply select the photo elements and process them with a single shared template. Here is a sample XSLT would shows this is done
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="yes"/>
<xsl:template match="/*">
<xsl:apply-templates select="Photo" />
</xsl:template>
<xsl:template match="Photo">
<xsl:value-of select="Text" />
<img src="{Image/@src}" />
</xsl:template>
</xsl:stylesheet>
This would output the following
This is the first Photo
<img src="http://cdn.theatlantic.com/static/infocus/ngpc112812/s_n01_nursingm.jpg">
This is the run picture
<img src="http://www.krav-maga.org.uk/uploads/images/news/running.jpg">
Also note the use of "Attribute Value Templates" in creating the src attribute for the image, which makes the XSLT neater to write.
Upvotes: 1