我有一个包含图像信息的简单XML文档。我需要将其转换为HTML – 简单,对吧?但是,当我使用下面的XSL时,它会出现错误“当没有元素开始标签打开时无法写入属性节点”。我看不到开放标签是什么 – 任何想法?
XML:
- <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<br /></p>
- </BodyText>
- <ShowLinkArrow>false</ShowLinkArrow>
- </root>
XSL:
- <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>
只是为了澄清这里的问题 – 错误在以下代码中:
- <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表达式。
注意,在这里可以使用与xsl_copy中使用的XPath相同的XPath,因为它在Attribute值模板中使用时知道采用文本值。