2014-03-24 1 views
0

노드 (이 경우 "User/ShopId")가 비어있는 경우 노드가 기본값 (예 : "0")으로 바뀌도록 XML 블록을 변환해야합니다.빈 노드의 기본값

어떻게 이것을 XSLT로 수행 할 수 있습니까?

XSLT 1.0

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

당신은 변경 될 수 있습니다

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

다른 변환을 처리하는 것을보다 선행 .

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