如何使用 xslt 填充文本模板 [英] how to fill text templates using xslt

查看:36
本文介绍了如何使用 xslt 填充文本模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含信息的 XML 文件,例如:

I have an XML file with information, for example:

<letter>
  <name>Test</name>
  <age>20</age>
  <me>Me</me>
</letter>

然后我有一个文本模板,如:

And then I have an text template like:

Dear $name,

some text with other variables like $age or $name again

greatings $me

当使用 xslt 将 XML 转换为纯文本字母时,我可以使用以下内容:

When using xslt to transform the XML to the plain text letter I can use something like:

<xsl:text>Dear </xsl:text><xsl:value-of select="name"/><xsl:text>

some text with other variables like </xsl:text>
<xsl:value-of select="age"/><xsl:text> or </xsl:text>
<xsl:value-of select="name"/><xsl:text> again

greatings </xsl:text><xsl:value-of select="me"/>

但是当我得到越来越多的变量和越来越多的文本时,这将成为输入和维护的噩梦.

But when I get more and more variables and more text this becomes a nightmare to enter and to maintain.

有什么方法可以使用 xslt 以更简洁的方式执行此操作吗?如果我可以使用上面作为示例使用的文本模板,并将 $name 和 $age 替换为正确的值,我更愿意.

Is there some way to do this in a cleaner way using xslt? I would prefer if I could just use the text template I used as an example above and have $name and $age replaced with the correct values.

推荐答案

此样式表:

<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:my="my">
    <xsl:output method="text"/>
    <xsl:preserve-space elements="my:layout"/>
    <my:layout>Dear <name/>,

some text with other variables like <age/> or <name/> again

greatings <me/></my:layout>
    <xsl:variable name="vData" select="/"/>
    <xsl:template match="/">
        <xsl:apply-templates select="document('')/*/my:layout/node()"/>
    </xsl:template>
    <xsl:template match="*/*">
        <xsl:value-of select="$vData//*[name()=name(current())]"/>
    </xsl:template>
</xsl:stylesheet>

输出:

Dear Test,

some text with other variables like 20 or Test again

greatings Me

注意:对于更复杂的填充模式(即迭代),请查看此帖子:与 XSLT 类似的 Sitemesh 功能?具有动态内容的 XSLT 布局区域

Note: For more complex population pattern (i.e. iteration), check this posts: Sitemesh like functionality with XSLT? and XSLT Layouts With Dynamic Content Region

这篇关于如何使用 xslt 填充文本模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆