XSLT替换空元素和属性值
问题描述:
在下面的XSLT我检查以下XSLT替换空元素和属性值
- 如果元素为null,则替换然后与其他元素的值替换它。
- 如果该元素的属性为null,则将其替换为常量值。
1正在工作,但2不是。
对于2我已经尝试了两件事情:
首先,使用xsl:if
条件没有工作。 它添加了一个具有相同节点名称的新节点,而不是将值插入属性。
第二我试图使用该模板。那也行不通。 它完全消除了该节点并将该属性添加到具有该值的父级。
此外,是否有可能以不同的方式或更好的方式做到这一点。
XSLT
<xsl:template match="//ns0:Cedent/ns0:Party/ns0:Id">
<xsl:if test="//ns0:Cedent/ns0:Party/ns0:Id = ''">
<xsl:copy>
<xsl:value-of select="//ns0:Broker/ns0:Party/ns0:Id"/>
</xsl:copy>
</xsl:if>
<!--<xsl:if test="//ns0:Cedent/ns0:Party/ns0:Id[@Agency = '']">
<xsl:copy>
<xsl:attribute name="Agency">Legacy</xsl:attribute>
<xsl:value-of select="'Legacy'"/>
</xsl:copy>
</xsl:if>-->
</xsl:template>
<xsl:template match="//ns0:Cedent/ns0:Party/ns0:Id[@Agency = '']">
<xsl:attribute name="Agency">Legacy</xsl:attribute>
</xsl:template>
输入
<ns0:Testing>
<ns0:Cedent>
<ns0:Party>
<ns0:Id Agency=""></ns0:Id>
<ns0:Name>Canada</ns0:Name>
</ns0:Party>
</ns0:Cedent>
<ns0:Broker>
<ns0:Party>
<ns0:Id Agency="Legacy">292320710</ns0:Id>
<ns0:Name>Spain</ns0:Name>
</ns0:Party>
</ns0:Broker>
</ns0:Testing>
输出
<ns0:Testing>
<ns0:Cedent>
<ns0:Party>
<ns0:Id Agency="Legacy">292320710</ns0:Id>
<ns0:Name>Canada</ns0:Name>
</ns0:Party>
</ns0:Cedent>
</ns0:Testing>
答
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ns0="some_namespace_uri"
>
<xsl:output indent="yes" />
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*" />
</xsl:copy>
</xsl:template>
<xsl:template match="ns0:Cedent/ns0:Party/ns0:Id[. = '']">
<xsl:copy>
<xsl:apply-templates select="@*" />
<xsl:apply-templates select="
../../following-sibling::ns0:Broker[1]/ns0:Party/ns0:Id/node()
" />
</xsl:copy>
</xsl:template>
<xsl:template match="ns0:Cedent/ns0:Party/ns0:Id/@Agency[. = '']">
<xsl:attribute name="Agency">Legacy</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
给你
<Testing xmlns="some_namespace_uri">
<Cedent>
<Party>
<Id Agency="Legacy">292320710</Id>
<Name>Canada</Name>
</Party>
</Cedent>
<Broker>
<Party>
<Id Agency="Legacy">292320710</Id>
<Name>Spain</Name>
</Party>
</Broker>
</Testing>
注:
-
,如果你不想在输出中
<Broker>
元素可言,添加一个空的模板:<xsl:template match="ns0:Broker" />
匹配表达式在模板中不需要从根节点开始。
- 样式表的作用是复制输入只有一些变化,比如这个,应该始终以标识模板开始。
感谢您的优雅的解决方案和解释。 – JohnXsl 2013-05-04 13:48:25