我需要转换XML块,以便在节点(在本例中为#34; User / ShopId")为空时 它应该回退到默认值,例如" 0"。
如何使用XSLT实现这一目标?
XSLT 1.0
<xsl:template match="/">
<Objects Version="product-0.0.1">
<xsl:apply-templates select='Users/User'/>
</Objects>
</xsl:template>
<xsl:template match="User">
<User>
<xsl:attribute name="Email"><xsl:value-of select="Email"/></xsl:attribute>
<xsl:attribute name="ShopId"><xsl:value-of select="ShopId"/></xsl:attribute>
<xsl:attribute name="ERPCustomer"><xsl:value-of select="ERPCustomer"/></xsl:attribute>
<xsl:attribute name="DisplayName"><xsl:value-of select="DisplayName"/></xsl:attribute>
</User>
</xsl:template>
例如
<Users>
<User>
<Email>asdasd@gmail.com</Email>
<ShopId>123123</ShopId>
<ERPCustomer>100</ERPCustomer>
<DisplayName>Username</DisplayName>
</User>
<User>
<Email>asdasd2@gmail.com</Email>
<ShopId></ShopId>
<ERPCustomer>100</ERPCustomer>
<DisplayName>Username</DisplayName>
</User>
<Users>
将转化为
<Objects Version="product-0.0.1">
<User Email="asdasd@gmail.com" ShopId="123123" ERPCustomer="100" DisplayName="Username"></User>
<User Email="asdasd2@gmail.com" ShopId="0" ERPCustomer="100" DisplayName="Username"></User>
</Objects>
答案 0 :(得分:3)
在您的代码示例中,您可以更改
<xsl:attribute name="ShopId"><xsl:value-of select="ShopId"/></xsl:attribute>
到
<xsl:attribute name="ShopId">
<xsl:choose>
<xsl:when test="not(normalize-space(ShopId))">0</xsl:when>
<xsl:otherwise><xsl:value-of select="ShopId"/></xsl:otherwise>
</xsl:choose>
</xsl:attribute>
我会考虑更改模板匹配方法并编写模板
<xsl:template match="Users/User/ShopId[not(normalize-space())]">
<xsl:attribute name="{name()}">0</xsl:attribute>
</xsl:template>
对于那个特殊情况,并在
之前<xsl:template match="Users/User/*">
<xsl:attribute name="{name()}"><xsl:value-of select="."/></xsl:attribute>
</xsl:template>
处理其他转换。
答案 1 :(得分:2)
您可以将“用户”的所有子元素转换为属性,然后选择创建其值:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml"/>
<xsl:template match="/">
<Objects Version="product-0.0.1">
<xsl:apply-templates select='Users/User'/>
</Objects>
</xsl:template>
<xsl:template match="User">
<xsl:copy>
<xsl:apply-templates />
</xsl:copy>
</xsl:template>
<xsl:template match="User/*">
<xsl:attribute name="{local-name(.)}">
<xsl:choose>
<xsl:when test=". != ''">
<xsl:value-of select="."/>
</xsl:when>
<xsl:otherwise>0</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>