【发布时间】:2015-12-14 12:19:15
【问题描述】:
我想在 XML 中插入一个缺失的节点,以防它丢失。例如,我想在 CustomInformation 节点之前添加一个<Details> 节点。我已经编写了下面的 XSLT 转换,但 CostPlan 节点上的属性没有出现。我哪里错了?
样本数据:
<CostPlan code="test" periodType="MONTHLY" >
<Description/>
<GroupingAttributes>
<GroupingAttribute>cost_type_id</GroupingAttribute>
<GroupingAttribute>transaction_class_id</GroupingAttribute>
<GroupingAttribute>charge_code_id</GroupingAttribute>
</GroupingAttributes>
<CustomInformation>
<ColumnValue name="pra">xyz</ColumnValue>
<ColumnValue name="partition_code">abc</ColumnValue>
</CustomInformation>
</CostPlan>
XSLT 转换:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*" name="identity">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="CostPlan[not(Details)]">
<xsl:variable name="elements-after" select="CustomInformation"/>
<xsl:copy>
<xsl:copy-of select="* except $elements-after"/>
<Details/>
<xsl:copy-of select="$elements-after"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
输出:
<CostPlan> <!-- attributes missing compared to original -->
<Description/>
<GroupingAttributes>
<GroupingAttribute>cost_type_id</GroupingAttribute>
<GroupingAttribute>transaction_class_id</GroupingAttribute>
<GroupingAttribute>charge_code_id</GroupingAttribute>
</GroupingAttributes>
<Details/>
<CustomInformation>
<ColumnValue name="pra">xyz</ColumnValue>
<ColumnValue name="partition_code">abc</ColumnValue>
</CustomInformation>
</CostPlan>
【问题讨论】: