问题描述
给出XML
<SystemInfo>
<Info>
<Name>ABC</Name>
<ID>ZZ</ID>
<Number>2332</Number>
<Date>2020-10-10</Date>
<Version>1.0</Version>
</Info>
<Info>
<Name>XYZ</Name>
<ID>ZZ</ID>
<Number>1234</Number>
<Date>2020-10-10</Date>
<Ind>X</Ind>
</Info>
<Info>
<Name>PQR</Name>
<ID>ZZ</ID>
<Number>1234</Number>
<Date>2020-10-10</Date>
<Ack>Y</Ack>
</Info>
</SystemInfo>
仅当Name ='XYZ'时,XSLT才应将新元素添加为'Info'标签的最后一个元素 预期输出如下。
<SystemInfo>
<Info>
<Name>ABC</Name>
<ID>ZZ</ID>
<Number>2332</Number>
<Date>2020-10-10</Date>
<Version>1.0</Version>
</Info>
<Info>
<Name>XYZ</Name>
<ID>ZZ</ID>
<Number>1234</Number>
<Date>2020-10-10</Date>
<Ind>X</Ind>
**<Type>P</Type>**
</Info>
<Info>
<Name>PQR</Name>
<ID>ZZ</ID>
<Number>1234</Number>
<Date>2020-10-10</Date>
<Ack>Y</Ack>
</Info>
</SystemInfo>
我尝试了以下两种方法。
第一次实施。
<xsl:template match="/|@*|node()">
<xsl:copy>
<xsl:apply-template select = "@*/node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="ns0:Info[./ns0:Name='XYZ']">
<xsl:apply-template select = "@*/node()" />
<xsl:element name="Type">P</xsl:element>
</xsl:template>
->结果>> Name ='XYZ'时缺少'Info'标记
第二实施。
<xsl:template match="/|@*|node()">
<xsl:copy>
<xsl:apply-template select = "@*/node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="ns0:Info[./ns0:Name='XYZ']">
<xsl:copy-of select = "." />
<xsl:element name="Type">P</xsl:element>
</xsl:template>
->结果>>“类型”显示在“信息”结束标记下方,而不是结束标记上方
预先感谢您的帮助
解决方法
您只需要对模板进行较小的更改:
<xsl:template match="Info[Name='XYZ']">
<xsl:copy>
<xsl:apply-templates select = "@* | node()" />
<xsl:element name="Type">P</xsl:element>
</xsl:copy>
</xsl:template>
如有必要,将名称空间ns0:
添加到您的匹配规则中,如下所示:
<xsl:template match="ns0:Info[ns0:Name='XYZ']">
...
请注意您的身份模板不正确的事实。正确的方法如下:
<!-- Identity template -->
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()" />
</xsl:copy>
</xsl:template>
其输出是:
<?xml version="1.0"?>
<SystemInfo>
<Info>
<Name>ABC</Name>
<ID>ZZ</ID>
<Number>2332</Number>
<Date>2020-10-10</Date>
<Version>1.0</Version>
</Info>
<Info>
<Name>XYZ</Name>
<ID>ZZ</ID>
<Number>1234</Number>
<Date>2020-10-10</Date>
<Ind>X</Ind>
<Type>P</Type> <!-- Added by template -->
</Info>
<Info>
<Name>PQR</Name>
<ID>ZZ</ID>
<Number>1234</Number>
<Date>2020-10-10</Date>
<Ack>Y</Ack>
</Info>
</SystemInfo>