XSLT将两个相同的元素合并为一个

时间:2017-06-01 07:35:20

标签: xslt-2.0

我一直在尝试使用XSLT 2.0合并两个相同的元素

示例源XML:

<?xml version="1.0" encoding="UTF-8"?>
<summary>
<object>
    <para>Paragraph <ref>Test1.</ref>AAA</para>
    <para>Test2.</para>
</object>
<objects>
    <para>
        <title>Title 1</title>: (1) Testing1</para>
    <para>(2) Testing 2</para>
    <para>Testing 3</para>
</objects>
<objects>
    <para>
        <title>Title 2</title>: Testing 4</para>
</objects>

所需的输出将是:

<summary>
<object>
    <para>Paragraph <ref>Test1.</ref>AAA</para>
    <para>Test2.</para>
</object>
<objects>
    <para>
        <title>Title 1</title>: (1) Testing1</para>
    <para>(2) Testing 2</para>
    <para>Testing 3</para>
    <para>
        <title>Title 2</title>: Testing 4</para>
</objects>
</summary>

我使用以下模板进行转换,遗憾的是它没有给我想要的结果..

<xsl:template match="summary">
    <xsl:for-each select="//objects">
        <xsl:element name="objects">
            <xsl:for-each select="//objects/*">
                <xsl:copy-of select="."/>
            </xsl:for-each>
        </xsl:element>
    </xsl:for-each>
</xsl:template>
<xsl:template match="*|@*|comment()|processing-instruction()|text()"  >
    <xsl:copy copy-namespaces="no">
        <xsl:apply-templates select="*|@*|comment()|processing-instruction()|text()" />
    </xsl:copy>
</xsl:template>

1 个答案:

答案 0 :(得分:0)

如果您只想合并所有objects兄弟元素,那么

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">


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

    <xsl:template match="objects[1]">
        <xsl:copy>
            <xsl:copy-of select="node(), following-sibling::objects/node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="objects[position() gt 1]"/>

</xsl:transform>

应该足够了。对于仅合并相邻的兄弟姐妹,您可以在匹配<xsl:for-each-group select="*" group-adjacent="boolean(self::objects)">...</xsl:for-each-group>或任何summary父级的模板中使用objects

相关问题