当前位置 : 主页 > 网页制作 > xml >

xml – XSLT Concat字段在一起

来源:互联网 收集:自由互联 发布时间:2021-06-13
我试图过滤特定的字段,并在另一个字段上连接: 输入: ?xml version="1.0" encoding="UTF-8"?payloads payload firstnamemichael/firstname secondnamebrown/secondname number1/number /payload payload firstnamemichael/firstname
我试图过滤特定的字段,并在另一个字段上连接:

输入:

<?xml version="1.0" encoding="UTF-8"?>
<payloads>
    <payload>
        <firstname>michael</firstname>
        <secondname>brown</secondname>
        <number>1</number>
    </payload>
    <payload>
        <firstname>michael</firstname>
        <secondname>brown</secondname>
        <number>2</number>
    </payload>
    <payload>
        <firstname>michael</firstname>
        <secondname>brown</secondname>
        <number>3</number>
    </payload>
</payloads>

输出:

<?xml version="1.0" encoding="UTF-8"?>
<payloads>
    <payload>
        <firstname>michael</firstname>
        <secondname>brown</secondname>
        <number>1,2,3</number>
    </payload>
</payloads>

我知道我需要遍历每个有效负载标签,但目前我无法正确输出它.目前我有这个:

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

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

    <xsl:template match="payloads">
        <xsl:copy>
            <xsl:for-each select="payload">
                <payload>
                    <xsl:value-of select="firstname"/>
                    <xsl:value-of select="secondname"/>
                    <xsl:value-of select="number"/>
                </payload>
            </xsl:for-each>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
使用此模板:

<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:key name="k" match="payload" use="concat(firstname, '|', secondname)"/>

    <xsl:template match="payload[generate-id() = 
                  generate-id(key('k', concat(firstname, '|', secondname)))]">
        <xsl:copy>
            <xsl:copy-of select="firstname"/>
            <xsl:copy-of select="secondname"/>
            <number>
                <xsl:for-each select="key('k', concat(firstname, '|', secondname))">
                    <xsl:value-of select="number"/>

                    <xsl:if test="position() != last()">
                        <xsl:text>,</xsl:text>
                    </xsl:if>
                </xsl:for-each>
            </number>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="payload"/>

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

当应用于提供的输入XML时,它输出想要的正确结果:

<payloads>
  <payload>
    <firstname>michael</firstname>
    <secondname>brown</secondname>
    <number>1,2,3</number>
  </payload>
</payloads>
网友评论