2014-03-24 40 views
0

我需要轉換一個XML塊,以便如果節點(在本例中爲「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>[email protected]</Email> 
    <ShopId>123123</ShopId> 
    <ERPCustomer>100</ERPCustomer> 
    <DisplayName>Username</DisplayName> 
    </User> 

    <User> 
    <Email>[email protected]</Email> 
    <ShopId></ShopId> 
    <ERPCustomer>100</ERPCustomer> 
    <DisplayName>Username</DisplayName> 
    </User> 
<Users> 

將被改造成

<Objects Version="product-0.0.1"> 
    <User Email="[email protected]" ShopId="123123" ERPCustomer="100" DisplayName="Username"></User> 
    <User Email="[email protected]" ShopId="0" ERPCustomer="100" DisplayName="Username"></User> 
</Objects> 

回答

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> 

對於特殊情況,preceed與

<xsl:template match="Users/User/*"> 
    <xsl:attribute name="{name()}"><xsl:value-of select="."/></xsl:attribute> 
</xsl:template> 

來處理其他轉換。

+0

感謝您的反饋意見,我一定會做到這一點。 – user634545

+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>