How do you access an element by its attribute value using XSL transformations and XML?

I am trying to convert an XML document to XHTML using an XSL transform and wondered how I can select an XML element, given the value of its attribute. eg.

<image size="small">http:example.small.jpg</image> <image size="medium">http:example.medium.jpg</image> <image size="large">http:example.largw.jpg</image> 

I want to access the value "http: example.medium.jpg" from the image tag, where size = "medium".

Any help is greatly appreciated.

Ally

+4
source share
4 answers
 <xsl:value-of select="image[@size='medium']" /> 
+7
source

This XPath expression will give you the result you need:

 //image[@size='medium'] 

This is a very simple XPath question. I suggest you familiarize yourself with some examples of the W3C School XPath tutorial , because XPath is a very expressive and useful tool.

To use this in an XSL stylesheet, you probably start with something like this:

 <xsl:template match="/"> <xsl:value-of select="//image[@size='medium']"/> </xsl:template> 

Again, this is a very simple XSL, so if you want to know more, I would advise you to take a look at the W3C School XSLT tutorial , Where I go when I need to see details about things that I may have forgotten.

+5
source

To clarify XPath expressions in three answers

 <xsl:template match="/"> <xsl:value-of select="//image[@size='medium']"/> </xsl:template> 

(@Welbog) will find EVERY image element in the document with size = "medium"

 <xsl:value-of select="image[@size = 'medium']" /> 

(@Murph and @carillonator) will only return an image element if it is a direct descendant of the current element. Since you did not specify the structure of your XML, you must be careful when evaluating this expression.

+2
source

This is a request with an extension - exactly how it will depend on the xslt structure, but taking into account the above, the template call will look like this:

 <xsl:apply-templates select="image[@size = 'medium']" /> 

Just select the value, erm:

 <xsl:value-of select="image[@size = 'medium']" /> 

The key in both cases is where, the bit in square brackets. To give a better answer, I would like to see more XML and XSLT

+1
source

All Articles