【问题标题】:Add parent node using XSLT使用 XSLT 添加父节点
【发布时间】:2014-04-04 18:30:15
【问题描述】:

我正在尝试使用 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>

【问题讨论】:

    标签: xslt-2.0


    【解决方案1】:

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

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

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

    【讨论】:

    • 那你应该accept@helderdarocha 的回答。
    猜你喜欢
    • 1970-01-01
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多