【问题标题】:In XSL, how to split a string from comma and replace the splitted substrings to other strings?在 XSL 中,如何从逗号拆分字符串并将拆分的子字符串替换为其他字符串?
【发布时间】:2015-07-07 07:26:35
【问题描述】:

我有一个这样的 XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <users>1, 2, 3</users>
</root>

我想将 ID 1、2、3 转换为各自的名称,例如“Albert”、“Brown”、“Clark”,并用“;”连接它们。 ID和名称是固定的,所以我只需简单地将名称与ID一一对应即可。 我想使用 XSLT 1.0,并以这种方式生成 XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <users>Albert;Brown;Clark</users>
</root>

我是 XSL 的新手,有什么建议可以帮助我完成这项工作吗?非常感谢!

【问题讨论】:

  • 这些名字从何而来? --附言请说明使用的是 XSLT 1.0 还是 2.0。
  • 也许可以遵循一些 XSL 教程,自己尝试一些东西,如果失败,添加你厌倦的代码,解释哪里出了问题/你不明白什么。
  • 我更新了我的问题。谢谢。

标签: xml xslt


【解决方案1】:

这里其实有两个问题:(1)如何对输入的字符串进行tokenize,(2)如何查找每个token code对应的名字。试试这个方法:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
extension-element-prefixes="exsl">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:variable name="users">
    <user code="1">Albert</user>
    <user code="2">Brown</user>
    <user code="3">Clark</user>
</xsl:variable>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="users">
    <xsl:copy>
        <xsl:call-template name="tokenize">
            <xsl:with-param name="text" select="."/>
        </xsl:call-template>        
    </xsl:copy>
</xsl:template>

<xsl:template name="tokenize">
    <xsl:param name="text"/>
    <xsl:param name="delimiter" select="', '"/>
    <xsl:variable name="code" select="substring-before(concat($text, $delimiter), $delimiter)" />
    <xsl:variable name="name" select="exsl:node-set($users)/user[@code=$code]" /> 
    <xsl:choose>
        <xsl:when test="$name">
            <xsl:value-of select="$name"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="concat('No user found for code', $code)"/>
        </xsl:otherwise>
    </xsl:choose>
    <xsl:if test="contains($text, $delimiter)">
        <xsl:text>;</xsl:text>
        <!-- recursive call -->
        <xsl:call-template name="tokenize">
            <xsl:with-param name="text" select="substring-after($text, $delimiter)"/>
        </xsl:call-template>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>

注意:您可以使用外部 XML 文档来保存代码索引并从那里查找名称,而不是变量,例如:XSLT- Copy node from other XML file, based on matching node value

【讨论】:

  • 非常感谢。您的解决方案适用于我的分离环境。我真的很想投票给你,但不幸的是我还没有足够的信用。我仍然有一些问题要在集成编译上下文中运行它,但我认为我已经接近它了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-18
  • 1970-01-01
  • 2019-05-22
  • 2011-11-25
相关资源
最近更新 更多