用动态数据替换占位符
Posted
技术标签:
【中文标题】用动态数据替换占位符【英文标题】:replace placeholder with dynamic data 【发布时间】:2018-04-23 19:25:00 【问题描述】:是否有使用 XSL 或 java.text.MessageFormat 实现以下目标的通用方法?
【问题讨论】:
【参考方案1】:如果您输入的 XML 如下:
<Order OrderNo="T122345">
<Customer FirstName="John" LastName="Doe" MobileNo="123456789"/>
<OrderDates>
<OrderDate Type="PickDate" Name="PickUpdateDate" Value="2017-11-10 10:00:00" />
</OrderDates>
</Order>
然后使用 XSL 如下:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"/>
<!--prepare message formatted template as below-->
<xsl:template name="message">
<xsl:param name="client.firstname"/>
<xsl:param name="client.lastname"/>
<xsl:param name="client.order.no"/>
<xsl:param name="client.pickup.date"/>
<xsl:param name="client.mobile.no"/>
<xsl:variable name="var.h" select="concat('
', 'hi ', $client.firstname, ' ', $client.lastname, ',', '
', '', '
')"/>
<xsl:variable name="var.b.str1" select="concat('Thanks for your order # is ', $client.order.no, '.', '
')"/>
<xsl:variable name="var.b.str2" select="concat('We will send you updates on pick up by ', $client.pickup.date, ' on your mobile # ', $client.mobile.no, '.', '
')"/>
<xsl:variable name="var.s" select="concat('', '
', 'Regards', '
', 'Team', '
')"/>
<Message>
<xsl:value-of select="concat($var.h, $var.b.str1, $var.b.str2, $var.s)"/>
</Message>
</xsl:template>
<!--run you formatted message template by call-template function-->
<xsl:template match="/Order">
<xsl:call-template name="message">
<xsl:with-param name="client.firstname" select="./Customer/@FirstName" />
<xsl:with-param name="client.lastname" select="./Customer/@LastName" />
<xsl:with-param name="client.order.no" select="./@OrderNo" />
<xsl:with-param name="client.pickup.date" select="./OrderDates/OrderDate[@Type = 'PickDate' and @Name = 'PickUpdateDate']/@Value" />
<!--below you can pass city code as below for mobile no-->
<xsl:with-param name="client.mobile.no" select="concat('91-', ./Customer/@MobileNo)" />
</xsl:call-template>
</xsl:template>
</xsl:stylesheet>
你会达到预期的效果:
<?xml version="1.0" encoding="UTF-8"?>
<Message>
hi John Doe,
Thanks for your order # is T122345.
We will send you updates on pick up by 2017-11-10 10:00:00 on your mobile # 91-123456789.
Regards
Team
</Message>
【讨论】:
以上是关于用动态数据替换占位符的主要内容,如果未能解决你的问题,请参考以下文章