XSLT使用内部结构的单个实例创建源消息的副本

时间:2018-06-27 16:45:20

标签: xml xslt

我想找到可以解决此问题的通用xslt转换。 假设有这个XML

<Train>
    <GeneralData>
        <TrainNumber>123</TrainNumber>
    </GeneralData>
    <ArrayOfCoaches>
        <Coach>
            <CoachNumber>1</CoachNumber>
            <CoachSeats>18</CoachSeats>
        </Coach>
        <Coach>
            <CoachNumber>2</CoachNumber>
            <CoachSeats>23</CoachSeats>
        </Coach>
        <Coach>
            <CoachNumber>3</CoachNumber>
            <CoachSeats>34</CoachSeats>
        </Coach>
    </ArrayOfCoaches>
</Train>

我希望能够“拆分”此消息,以创建仅包含一个这样的Coach的多个部分

<ArrayOfTrainCoaches>
    <Train>
        <GeneralData>
            <TrainNumber>123</TrainNumber>
        </GeneralData>
        <ArrayOfCoaches>
            <Coach>
                <CoachNumber>1</CoachNumber>
                <CoachSeats>18</CoachSeats>
            </Coach>
        </ArrayOfCoaches>
    </Train>
    <Train>
        <GeneralData>
            <TrainNumber>123</TrainNumber>
        </GeneralData>
        <ArrayOfCoaches>
            <Coach>
                <CoachNumber>2</CoachNumber>
                <CoachSeats>23</CoachSeats>
            </Coach>
        </ArrayOfCoaches>
    </Train>
    <Train>
        <GeneralData>
            <TrainNumber>123</TrainNumber>
        </GeneralData>
        <ArrayOfCoaches>
            <Coach>
                <CoachNumber>3</CoachNumber>
                <CoachSeats>34</CoachSeats>
            </Coach>
        </ArrayOfCoaches>
    </Train>
</ArrayOfTrainCoaches>

我不清楚如何使用for-each复制整个邮件,除了某些子结构,我想将其拆分为整个邮件的专用副本。

谢谢您的帮助。

2 个答案:

答案 0 :(得分:1)

看起来像:

<ArrayOfTrainCoaches>
  <xsl:for-each select="//Coach">
    <Train>
        <xsl:copy-of select="//GeneralData"/>
        <ArrayOfCoaches>
            <xsl:copy-of select="."/>
        </ArrayOfCoaches>
    </Train>
  </xsl:for-each>
</ArrayOfTrainCoaches>

答案 1 :(得分:0)

<xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="Train">
        <ArrayOfTrainCoaches>
        <xsl:for-each select="ArrayOfCoaches/Coach">

            <Train>
                <xsl:copy-of select="ancestor::Train/GeneralData"/>
                <ArrayOfCoaches>
                <xsl:copy-of select="."/>
                    </ArrayOfCoaches>
            </Train>

        </xsl:for-each>
            </ArrayOfTrainCoaches>
    </xsl:template>
Look it