字符串替换和串联 [英] String replace and concatenation

查看:56
本文介绍了字符串替换和串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种结构

<ROWS>
  <ROW>
    <TEXT> This is a @good@ @day@ </TEXT>
    <good>great</good>
    <day>month</day>
  </ROW>
  <ROW>
    <TEXT> This is a @good@ @day@ </TEXT>
    <good>Fun</good>
    <day>morning</day>
  </ROW>
</ROWS>

如何将其更改为

<statement> This is a great month, this is a Fun morning </statement>

仅使用XSLT 1.0吗?

Using only XSLT 1.0?

原始XML可以更改标签名称。但不是结构!有任何想法吗?

The original XML can change tag name. But not the structure! Any ideas?

推荐答案

这似乎有点类似于从模板创建套用信函。假设该示例并非字面上的意思,您可以尝试以下类似方法:

This seems somewhat similar to creating form letters from a template. Assuming the example is not to be meant literally, you could try something like:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
    <statements>
        <xsl:for-each select="ROWS/ROW/TEXT">
            <statement>
                <xsl:call-template name="merge">
                    <xsl:with-param name="string" select="."/>
                </xsl:call-template>
            </statement>
        </xsl:for-each>
    </statements>
</xsl:template>

<xsl:template name="merge">
    <xsl:param name="string"/>
    <xsl:param name="sep" select="'@'"/>
    <xsl:choose>
        <xsl:when test="contains($string, $sep) and contains(substring-after($string, $sep), $sep)">
            <xsl:value-of select="substring-before($string, $sep)" />
            <xsl:variable name="placeholder" select="substring-before(substring-after($string, $sep), $sep)" />
            <xsl:value-of select="../*[name() = $placeholder]" />
            <!-- recursive call -->
            <xsl:call-template name="merge">
                <xsl:with-param name="string" select="substring-after(substring-after($string, $sep), $sep)" />
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$string" />
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

</xsl:stylesheet>

输入以下内容:

<ROWS>
  <ROW>
    <TEXT>The quick brown @animal@ jumps over the @property@ dog.</TEXT>
    <animal>fox</animal>
    <property>lazy</property>
  </ROW>
  <ROW>
    <TEXT>A journey of a @number@ miles @action@ with a single @act@.</TEXT>
    <number>thousand</number>
    <action>begins</action>
    <act>step</act>
  </ROW>
</ROWS>

结果将是:

<?xml version="1.0" encoding="UTF-8"?>
<statements>
   <statement>The quick brown fox jumps over the lazy dog.</statement>
   <statement>A journey of a thousand miles begins with a single step.</statement>
</statements>

这篇关于字符串替换和串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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