代码之家  ›  专栏  ›  技术社区  ›  Lena S

xslt:将某些元素复制为另一个元素的子元素

  •  0
  • Lena S  · 技术社区  · 6 年前

    我知道这种转变是微不足道的,但不幸的是我被困住了。 我的输入如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <tests>
        <test>Biography</test>
        <test>Job</test>
        <test>Salary</test>
        <test>FirtsName</test>
        <test>John</test>
        <test>Mary</test>
        <test>David</test>
        <test>Isabella</test>
        <test>SecondName</test>
        <test>Jones</test>
        <test>Williams</test>
        <test>Biography</test>
        <test>Job</test>
        <test>Salary</test>
        <test>FirtsName</test>
        <test>Paul</test>
        <test>Peter</test>
        <test>SecondName</test>
        <test>Castro</test>
        <test>Ricci</test>
    <tests>
    

    我要做的是,使用xslt 2.0,在元素“test”和元素“test”之间选择值为“firstname”的元素“test”和值为“secondname”的元素“test”,并将它们复制为其第一个前面的“test”元素的子元素,值为“biography”。 这个 产量 应该像这样。

    <?xml version="1.0" encoding="UTF-8"?>
    <tests>
        <test>Biography
            <test>John</test>
            <test>Mary</test>
            <test>David</test>
            <test>Isabella</test>
        </test>
        <test>Job</test>
        <test>Salary</test>
        <test>FirtsName</test>
        <test>SecondName</test>
        <test>Jones</test>
        <test>Williams</test>
        <test>Biography
            <test>Paul</test>
            <test>Peter</test>
        </test>
        <test>Job</test>
        <test>Salary</test>
        <test>FirtsName</test>
        <test>SecondName</test>
        <test>Castro</test>
        <test>Ricci</test>
    </tests>
    

    非常感谢您的帮助:)

    1 回复  |  直到 6 年前
        1
  •  0
  •   michael.hor257k    6 年前

    看看这是否有帮助:

    XSLT 2

    <xsl:stylesheet version="2.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="/tests">
        <xsl:copy>
            <xsl:for-each-group select="test" group-starting-with="test[.='Biography']">
                <xsl:variable name="names" select="current-group()[. >> current-group()[.='FirtsName'] and . &lt;&lt; current-group()[.='SecondName']]" />
                <test>
                   <xsl:value-of select="current-group()[1]"/> 
                   <xsl:text>&#10;</xsl:text>
                   <xsl:copy-of select="$names"/>
                </test>
                <xsl:copy-of select="current-group()[position() gt 1] except $names" />
            </xsl:for-each-group>
        </xsl:copy>
    </xsl:template>
    
    </xsl:stylesheet>
    

    演示 : https://xsltfiddle.liberty-development.net/94hvTAk