我正在尝试使用 XSLT 将父元素添加到 XML 中,但没有得到预期的结果。请参阅我的 XML 和 XSL 代码。我的转换在新添加的节点下添加了所有子节点,但我只期望新添加的标签下的文档参考。
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>
您可以通过显式命名父节点下需要哪些元素来选择它们。这将仅将DocumentReference
置于Kiran
之下。
<xsl:copy>
<Kiran>
<xsl:apply-templates select="@*|DocumentReference"/>
</Kiran>
<xsl:apply-templates select="@*|Item|Quantity"/>
</xsl:copy>
这是一个快速而简单的解决方案,但是如果您使用更通用的解决方案,您也可以通过其他方式(例如:使用xsl:if
,xsl:choose
或其他模板)编写更多代码来获得相同的结果。