我最近问了一个类似的问题 Convert text string to xml tagging using xsl pt.2 并收到了解决方案,它帮助我整理了一些 XSL-FO 代码。
现在,我尝试转换的 XML 是
<p>The @c cmdname is a utility and @v varname is an option.<p>
类似:
cmdname
是一个实用程序,varname是一个选项。
我使用以下 XSL-FO 将“@c”(cmdname)后面的单词转换为等宽字体,并将“@v”(varname)后面的单词转换为斜体。但是,在使用 XML 示例之类的句子构建 PDF 后,只有 @c (cmdname) 的字体发生变化。请注意,示例中的
<p>
标签可以是任何 XML 标签。
这是一个很长的故事,但我不能只使用 XML 标签,例如
<i>
来使字体变为斜体。
我的 XSL-FO 代码如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
<xsl:template match="text()[contains(., '@c')]">
<xsl:analyze-string select="." regex="@c\s+([!-~]+)">
<xsl:matching-substring>
<fo:inline font-family="RobotoMono-Regular">
<xsl:value-of select="regex-group(1)"/>
</fo:inline>
</xsl:matching-substring>
<xsl:non-matching-substring>
<xsl:value-of select="."/>
</xsl:non-matching-substring>
</xsl:analyze-string>
</xsl:template>
<xsl:template match="text()[contains(., '@v')]">
<xsl:analyze-string select="." regex="@v\s+([!-~]+)">
<xsl:matching-substring>
<fo:inline font-family="Roboto" font-style="italic">
<xsl:value-of select="regex-group(1)"/>
</fo:inline>
</xsl:matching-substring>
<xsl:non-matching-substring>
<xsl:value-of select="."/>
</xsl:non-matching-substring>
</xsl:analyze-string>
</xsl:template>
</xsl:stylesheet>
如何修改此 XSL-FO 代码以与任何“@*”标记组合一起使用?
您可以执行诸如捕获
@
之后的字母之类的操作,并使用它来确定 fo:inline
中应使用哪些属性(也许使用 xsl:use-attribute-sets
)。
示例...
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format"
version="2.0">
<xsl:strip-space elements="*"/>
<xsl:output indent="yes"/>
<xsl:template match="/doc">
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
<fo:layout-master-set>
<fo:simple-page-master master-name="sample">
<fo:region-body/>
</fo:simple-page-master>
</fo:layout-master-set>
<fo:page-sequence master-reference="sample">
<fo:flow flow-name="xsl-region-body">
<xsl:apply-templates/>
</fo:flow>
</fo:page-sequence>
</fo:root>
</xsl:template>
<xsl:template match="p">
<fo:block>
<xsl:apply-templates/>
</fo:block>
</xsl:template>
<xsl:attribute-set name="at_c">
<xsl:attribute name="font-family" select="'RobotoMono-Regular'"/>
</xsl:attribute-set>
<xsl:attribute-set name="at_v">
<xsl:attribute name="font-family" select="'Roboto'"/>
<xsl:attribute name="font-style" select="'italic'"/>
</xsl:attribute-set>
<xsl:template match="text()[matches(.,'@[cv]\s+\w+')]">
<xsl:analyze-string select="." regex="@([cv])\s+(\w+)">
<xsl:matching-substring>
<xsl:choose>
<xsl:when test="regex-group(1)='c'">
<fo:inline xsl:use-attribute-sets="at_c">
<xsl:value-of select="regex-group(2)"/>
</fo:inline>
</xsl:when>
<xsl:when test="regex-group(1)='v'">
<fo:inline xsl:use-attribute-sets="at_v">
<xsl:value-of select="regex-group(2)"/>
</fo:inline>
</xsl:when>
</xsl:choose>
</xsl:matching-substring>
<xsl:non-matching-substring>
<xsl:value-of select="."/>
</xsl:non-matching-substring>
</xsl:analyze-string>
</xsl:template>
</xsl:stylesheet>