如何通过XSL模板为XML输出内容应用字体大小与颜色样式
XSL输出内容应用字体样式的实现方案
样式调整不生效的核心原因
你之前调整样式没有效果,本质是两个基础问题导致的:
- XSL默认输出无结构的纯文本,没有可承载样式规则的标签节点,直接书写的样式规则不会被解析为样式效果
- 模板本身存在语法问题:把
<xsl:apply-templates>直接放在<xsl:stylesheet>顶级节点下,没有挂载到匹配XML根节点的模板内,转换流程本身就无法正常执行
可以根据实际输出目标,选择对应的实现路径:
方案1:输出为可在浏览器展示的HTML格式(通用场景)
这种场景下只需要用带内联样式的HTML标签包裹输出内容,即可快速实现字体、颜色调整,修正后的可运行完整代码如下:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 声明输出为HTML格式,去除多余的XML声明 --> <xsl:output method="html" indent="yes" omit-xml-declaration="yes"/> <!-- 匹配XML文档根节点的基础模板 --> <xsl:template match="/"> <html> <body> <!-- 容器级样式可批量应用到所有子内容 --> <div style="font-size:16px; color:#2c3e50; font-family:微软雅黑, sans-serif; line-height:2;"> <xsl:apply-templates select="//Node1"/> </div> </body> </html> </xsl:template> <xsl:template match="Node1"> <!-- 单行内容可单独设置专属样式 --> <p>Value# 1 = <xsl:value-of select="@attribute1"/></p> <p style="color:#e74c3c; font-size:18px;">Value# 2 = <xsl:value-of select="@attribute2"/></p> <p style="font-weight:bold;">Value# 3 = <xsl:value-of select="@attribute3"/></p> </xsl:template> </xsl:stylesheet>
可自由调整的常见样式参数包括:
color:设置文字颜色font-size:设置字号(支持px、em等通用单位)font-weight:设置文字是否加粗font-family:设置显示字体
原模板中引入的
msxsl、jscript命名空间如果没有配套脚本逻辑,可以直接删除,不会影响转换效果。
方案2:输出为XSL-FO格式(用于PDF生成、打印版式场景)
如果转换目标是生成用于排版印刷的FO格式文档,需要将内容包裹在<fo:block>节点内,通过节点属性直接设置样式,示例代码如下:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format"> <!-- 声明输出为标准XML格式的FO文档 --> <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <fo:root> <fo:layout-master-set> <fo:simple-page-master master-name="A4"> <fo:region-body margin="2cm"/> </fo:simple-page-master> </fo:layout-master-set> <fo:page-sequence master-reference="A4"> <fo:flow flow-name="xsl-region-body"> <xsl:apply-templates select="//Node1"/> </fo:flow> </fo:page-sequence> </fo:root> </xsl:template> <xsl:template match="Node1"> <fo:block font-size="16pt" color="#333333" font-family="SimSun"> Value# 1 = <xsl:value-of select="@attribute1"/> </fo:block> <fo:block font-size="18pt" color="red" space-before="10pt"> Value# 2 = <xsl:value-of select="@attribute2"/> </fo:block> <fo:block font-size="16pt" font-weight="bold" space-before="10pt"> Value# 3 = <xsl:value-of select="@attribute3"/> </fo:block> </xsl:template> </xsl:stylesheet>
注意:纯文本输出模式下,所有HTML、FO标签都会被当成普通文字直接输出,无法实现样式效果,调整样式前一定要先确认对应输出模式的格式要求。
内容的提问来源于stack exchange,提问作者Bhajan
相关产品推荐
相关产品推荐

