开发者

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

Im trying to transform an XML document into XHTML using XSL transformation and was wondering how i can choose an XML e开发者_如何转开发lement given the value of its attribute. e.g.

<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 only want to access the value "http:example.medium.jpg" from the image tag where size="medium".

Any help is greatly appreciated.

Ally


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


This XPath expression will get you the result you need:

//image[@size='medium']

This is a very basic XPath question. I'd suggest that you go through some of the example on W3C School's XPath tutorial, since XPath is a very expressive and useful tool.

To use this within an XSL stylesheet, you'd probably start with something like this:

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

Again, this is very basic XSL, so if you want to learn more I'd suggest you take a look at W3C School's XSLT tutorial. That's where I go when I need to look up details about things I may have forgotten.


To clarify the XPath expressions in the 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 the direct child of the current element. Since you didn't specify the structure of your XML you should be careful where you evaluate this expression.


This is an expath query - exactly how will depend on the structure of the xslt but given the above, calling a template would look like:

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

Just selecting the value, erm:

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

The key in both cases is the "where" which is the bit in square brackets. To give a better answer I'd want to see more of the XML and XSLT

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜