2013-05-11 77 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