首页 文章

你如何添加图像?

提问于
浏览
17

Situation:

我有一个包含图像信息的简单XML文档 . 我需要将其转换为HTML . 但是,我无法看到打开标记的位置,当我使用下面的XSL代码时,它显示以下错误消息:

“当没有元素开始标记打开时,无法写入属性节点 . ”

XML content:

<root>
    <HeaderText>
        <HeaderText>Dan Testing</HeaderText>
    </HeaderText>
    <Image>
        <img width="100" height="100" alt="FPO lady" src="/uploadedImages/temp_photo_small.jpg"/>
    </Image>
    <BodyText>
        <p>This is a test of the body text
</p> </BodyText> <ShowLinkArrow>false</ShowLinkArrow> </root>

XSL code:

<xsl:stylesheet version="1.0" extension-element-prefixes="msxsl"
    exclude-result-prefixes="msxsl js dl" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:js="urn:custom-javascript" xmlns:msxsl="urn:schemas-microsoft-com:xslt"
    xmlns:dl="urn:datalist">
    <xsl:output method="xml" version="1.0" omit-xml-declaration="yes" indent="yes" encoding="utf-8"/>
    <xsl:template match="/" xml:space="preserve">
        <img>
            <xsl:attribute name="width">
                100
            </xsl:attribute>
            <xsl:attribute name="height">
                100
            </xsl:attribute>
            <xsl:attribute name="class">
                CalloutRightPhoto
            </xsl:attribute>
            <xsl:attribute name="src">
                <xsl:copy-of select="/root/Image/node()"/>
            </xsl:attribute>
        </img>
    </xsl:template>
</xsl:stylesheet>

5 回答

  • 27

    只是为了澄清这里的问题 - 错误在以下代码中:

    <xsl:attribute name="src">
        <xsl:copy-of select="/root/Image/node()"/>
    </xsl:attribute>
    

    指令xsl:copy-of接受节点或节点集并复制它 - 输出节点或节点集 . 但是,属性不能包含节点,只能包含文本值,因此xsl:value-of将是一种可能的解决方案(因为它返回节点或节点集的文本值) .

    以下是一个更短的解决方案(也许更优雅):

    <img width="100" height="100" src="{/root/Image/node()}" class="CalloutRightPhoto"/>
    

    在属性中使用{}称为属性值模板,并且可以包含任何XPATH表达式 .

    注意,这里可以使用相同的XPath,就像在xsl_copy-of中使用的那样,因为它知道在属性值模板中使用时采用文本值 .

  • 3

    不应该是:

    <xsl:value-of select="/root/Image/img/@src"/>
    

    ?看起来您正在尝试将整个Image / img节点复制到属性@src

  • 4

    为了添加属性,XSL想要

    <xsl:element name="img">
         (attributes)
    </xsl:element>
    

    而不仅仅是

    <img>
         (attributes)
    </img>
    

    虽然,是的,如果您只是按原样复制元素,则不需要任何元素 .

  • 4

    没关系 - 我是个白痴 . 我只需要 <xsl:value-of select="/root/Image/node()"/>

  • 0

    尝试的另一种选择是直截了当的

    <img width="100" height="100" src="/root/Image/image.jpeg" class="CalloutRightPhoto"/>
    

    即没有{}而是给出直接图像路径

相关问题