如何根据条件移动XML元素

时间:2016-10-13 20:06:55

标签: xslt xslt-1.0 xslt-2.0

我有一个XML:

/search/accounts/3/2015 

我想从 AddedBOMs / BOMHeader 移动 StartEffectivity EndEffectivity ,但它应该与 ../ ..链接/ BOMComponent / PartNumber 即BOMComponent中的任何一个零件编号与BOMHeader的编号相匹配,它在BOMComponent中复制了相应的StartEffectivity和EndEffectivity

预期产出:

<?xml version="1.0" encoding="UTF-8"?>
<COLLECTION>
<AddedBOMs NAME="AddedBOMs" TYPE="Unknown" STATUS="0">
<BOMHeader>
    <Number>One</Number>
    <StartEffectivity>One 00:00:00</StartEffectivity>
    <EndEffectivity>One 00:00:00</EndEffectivity>
</BOMHeader>
</AddedBOMs>
<ChangedBOMs NAME="ChangedBOMs" TYPE="Unknown" STATUS="0">
<BOMHeader>
    <Number>Two</Number>
    <StartEffectivity>Two 00:00:00</StartEffectivity>
    <EndEffectivity>Two 00:00:00</EndEffectivity>
</BOMHeader>
</ChangedBOMs>
<UnchangedBOMs NAME="UnchangedBOMs" TYPE="Unknown" STATUS="0">
<BOMHeader>
    <Number>Three</Number>
    <StartEffectivity>Three 00:00:00</StartEffectivity>
    <EndEffectivity>Three 00:00:00</EndEffectivity>
</BOMHeader>
</UnchangedBOMs>
<DeletedBOMComponents NAME="DeletedBOMComponents" TYPE="Unknown" STATUS="0">
<BOMComponent>
    <PartNumber>Three</PartNumber>
</BOMComponent>
</DeletedBOMComponents>
<AddedBOMComponents NAME="AddedBOMComponents" TYPE="Unknown" STATUS="0">
<BOMComponent>
    <PartNumber>Two</PartNumber>
</BOMComponent>
</AddedBOMComponents>
<ChangedBOMComponents NAME="ChangedBOMComponents" TYPE="Unknown" STATUS="0">
<BOMComponent>
    <PartNumber>One</PartNumber>
</BOMComponent>
</ChangedBOMComponents>
</COLLECTION>

1 个答案:

答案 0 :(得分:0)

这里需要应用的逻辑一点也不清楚。假设您只想复制&#34;组件&#34;,在从相应的BOMHeader复制节点时,请尝试:

XSLT 1.0

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

<xsl:key name="header" match="BOMHeader" use="Number" />

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

<xsl:template match="/COLLECTION">
    <xsl:copy>
        <xsl:apply-templates select="*[BOMComponent]"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="BOMComponent">
    <xsl:variable name="head" select="key('header', PartNumber)" />
    <xsl:copy>
        <xsl:copy-of select="PartNumber"/>
        <xsl:copy-of select="$head/StartEffectivity | $head/EndEffectivity"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>