使用XSLT添加父节点

时间:2014-04-04 18:30:16

标签: xslt-2.0

我正在尝试使用XSLT将父元素添加到XML中,但是没有得到预期的结果。请参阅我的XML和XSL代码。我的转换在新添加的节点下添加了所有子节点,但我期望在新添加的标签下只有DocumentReference。

XML文件

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<DataArea>
    <PurchaseOrder>
        <PurchaseOrderLine>
            <DocumentReference>
                    <DocumentID>
                        <ID>23423</ID>
                    </DocumentID>
            </DocumentReference>
            <DocumentReference>
                <DocumentID>
                    <ID>23424</ID>
                </DocumentID>
            </DocumentReference>
            <Item>
                <CustomerItemID>
                    <!-- ArtNr -->
                    <ID>444</ID>
                </CustomerItemID>
            </Item>
            <Quantity unitCode="PCE">17.3</Quantity>
        </PurchaseOrderLine>
    </PurchaseOrder>
</DataArea>

预期结果

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<DataArea>
     <PurchaseOrder>
          <PurchaseOrderLine>
            <Kiran>
            <DocumentReference>
                <DocumentID>
                     <ID>23423</ID>
                 </DocumentID>
             </DocumentReference>
             <DocumentReference>
                 <DocumentID>
                     <ID>23424</ID>
                 </DocumentID>
              </DocumentReference>
            </Kiran>>
            <Item>
                <CustomerItemID>
                    <!-- ArtNr -->
                    <ID>444</ID>
                </CustomerItemID>
            </Item>
            <Quantity unitCode="PCE">17.3</Quantity>
        </PurchaseOrderLine>
        </PurchaseOrder>
 </DataArea>

XSLT代码

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>

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

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

1 个答案:

答案 0 :(得分:1)

您可以通过明确命名父节点来选择所需的元素。这只会在DocumentReference下放置Kiran

<xsl:copy>
    <Kiran>
        <xsl:apply-templates select="@*|DocumentReference"/>
    </Kiran>
    <xsl:apply-templates select="@*|Item|Quantity"/>
</xsl:copy>

这是一个快速而简单的解决方案,但如果你更通用的东西,你也可以通过其他方式(例如:使用xsl:ifxsl:choose或其他模板)获得相同的结果代码。