【问题标题】:Getting the value of an attribute in an XML document using XSL使用 XSL 获取 XML 文档中属性的值
【发布时间】:2012-06-01 16:02:56
【问题描述】:

我试图在我的 XSL 转换过程中获取 iWantToGetThis.jpg 的值并将其放入 <img> 中。这就是我的 xml 的结构:

<article>
    <info>
        <mediaobject>
            <imageobject>
                <imagedata fileref='iWantToGetThis.jpg'>

这是我为 XSL 提出的建议:

<xsl:template name="user.header.content">
    <xsl:stylesheet xmlns:d='http://docbook.org/ns/docbook'>
        <img><xsl:attribute name="src">../icons/<xsl:value-of select='ancestor-or-self::d:article/info/mediaobject/imageobject/imagedata/@fileref' /></xsl:attribute></img>
    </xsl:stylesheet>
</xsl:template>

图像被添加到输出中,但 src 属性设置为“../icons/”,所以我假设它没有在 XML 中找到 fileref 属性。这对我来说看起来完全有效,所以我不确定我错过了什么。

【问题讨论】:

    标签: xslt xpath docbook-5


    【解决方案1】:

    我不知道你怎么能得到任何东西,因为它看起来不像一个有效的 XSLT 文档(我预计会出现错误“Keyword xsl:stylesheet may not contain img.”)。

    但是,您可能只是展示了一段代码。如果是这种情况,您的问题可能是您只为 article 元素指定了命名空间,而您确实需要为 xpath 中的所有元素指定它。试试这个

    <xsl:value-of 
       select="ancestor-or-self::d:article/d:info/d:mediaobject/d:imageobject/d:imagedata/@fileref"/>
    

    另一个可能的问题可能是因为您使用 'ancestor-or-self' xpath 轴来查找属性。这仅在您当前的上下文已经在 article 元素或其后代之一上时才有效。

    附带说明,您可以在此处使用属性值模板来简化代码

    <img src="../icons/{ancestor-or-self::d:article/d:info/d:mediaobject/d:imageobject/d:imagedata/@fileref}" />
    

    【讨论】:

    • 这只是在 xpath 表达式中缺少子级命名空间。
    • 当完整的表单只包含一个 &lt;xsl:template match="/"&gt; 元素时,这种样式表是允许的。样式表仅包含该模板元素的内容。 Read about it here.
    • 我正在使用的 XSL 更加充实。发布后我意识到这不是一个很好的 XSL 示例...
    猜你喜欢
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    相关资源
    最近更新 更多