如何在 XSL 中按顺序将所有消息连接在一起



假设我得到以下XML:

<Gift>
            <GiftWrapId>026272275</GiftWrapId>
            <ClientIItemId>191267166704</ClientIItemId>
            <GiftMessageSequence>1</GiftMessageSequence>
            <GiftMessageType>GIFT</GiftMessageType>
            <GiftMessage>Happy Birthday, sweet</GiftMessage>
        </Gift>
        <Gift>
            <GiftWrapId>026272275</GiftWrapId>
            <ClientIItemId>191267166704</ClientIItemId>
            <GiftMessageSequence>2</GiftMessageSequence>
            <GiftMessageType>GIFT</GiftMessageType>
            <GiftMessage>Konnie</GiftMessage>
        </Gift>

我希望结果是"生日快乐,亲爱的Konnie",但按照"GiftMessageSequence"标签中提到的顺序连接"GiftMessage":

<CommentInfo>
 <CommentType>X</CommentType>
  <xsl:element name="CommentText">
   <xsl:value-of select="*Happy Birthday, sweet Konnie should come here*"/>
  </xsl:element>
</CommentInfo>

假设<GiftMessageSequence>具有数值,则可以在节点上执行排序,然后在<GiftMessage>中连接该值以获取完整的消息。

将输入 XML 包装在 <root> 节点中并对其应用以下 XSLT,将提供所需的输出。

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"  />
    <xsl:strip-space elements="*" />
    <xsl:template match="root">
        <xsl:variable name="message">
            <xsl:for-each select="Gift">
                <xsl:sort select="GiftMessageSequence" data-type="number" order="ascending" />
                <xsl:value-of select="concat(GiftMessage, ' ')" />
            </xsl:for-each>
        </xsl:variable>
        <CommentInfo>
            <CommentType>X</CommentType>
            <CommontText>
                <xsl:value-of select="normalize-space($message)" />
            </CommontText>
        </CommentInfo>
    </xsl:template>
</xsl:stylesheet>

输出

<CommentInfo>
    <CommentType>X</CommentType>
    <CommontText>Happy Birthday, sweet Konnie</CommontText>
</CommentInfo>

由于您的源包含多个Gift标签,因此它们必须是包含在某个标记中(为了形成正确的 XML(。

然后,在 XSLT 2.0 中,脚本可以如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>
  <xsl:template match="/">
    <CommentInfo>
      <CommentType>X</CommentType>
      <CommentText>
        <xsl:variable name="msg">
          <xsl:for-each select="*/Gift">
            <xsl:sort select="GiftMessageSequence"/>
            <xsl:copy-of select="."/>
          </xsl:for-each>
        </xsl:variable>
        <xsl:value-of select="$msg/Gift//GiftMessage"/>
      </CommentText>
    </CommentInfo>
  </xsl:template>
</xsl:stylesheet>

msg变量收集所有Gift元素,并按 GiftMessageSequence .请注意,XPath 表达式从 * 开始,以匹配任何根标记名称。

XSLT 2.0 中的value-of指令打印所有选定标记的值,默认分隔符等于空格。

最新更新