2013-05-11 80 views
1

我的目標是使用我的xml(版本1.0)和xsl(版本1.0)文件來創建html頁面。混淆:如何通過XSL中的ID選擇XML內容

這是我的XML文件中的代碼:

<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> 

我想用自己的ID來選擇我的XML文檔的各個部分。我還會用其他文字或段落來做這件事,我也會給出一個ID。目前,我正在使用for-each函數一次呈現所有圖像,但我不知道我究竟可以如何選擇單個文件。我在想是這樣的:

<xsl:value-of select="Photo/Text[one]"/> 
<img> 
<xsl:attribute name="src" id="one"> 
<xsl:value-of select="Photo/Image/@src"/> 
</xsl:attribute> 
</img> 

<xsl:value-of select="Photo/Text[run]"/> 
<img> 
<xsl:attribute name="src" id="run"> 
<xsl:value-of select="Photo/Image/@src"/> 
</xsl:attribute> 
</img> 

但它不工作:(我想我可以,但我失去了你能幫我

回答

1

?你正在尋找的語法是這樣的

<xsl:value-of select="Photo/Text[@id='one']" /> 

<xsl:value-of select="Photo/Image[@id='one']/@src" /> 

但是,您可能不希望爲每個可能的@id重複此編碼。在這裏使用模板匹配很容易,只需選擇照片元素並使用單個共享模板處理它們。這裏有一個簡單的XSLT會顯示這樣做

<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 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"> 

還要注意使用「屬性值模板」中創建的圖像SRC屬性,這使得XSLT整理者可以編寫。

+0

+1不錯,完整。 – Tomalak 2013-05-11 18:30:54