2010-01-26 7 views
5

apply-templates 선언이 모두과 일치해야한다고 생각합니다.`apply-templates` matching 이해하기

<doc> 
    <foo bar="1" baz="2">boz</foo> 
</doc> 

다음과 같은 스타일 : I 출력 될 기대

<xsl:template match="/"> 
    <xsl:apply-templates select="foo" mode="xyz" /> 
</xsl:template> 

<xsl:template mode="xyz" match="foo[bar='1']"> 
    abc 
</xsl:template> 

<xsl:template mode="xyz" match="foo[baz='2']"> 
    def 
</xsl:template> 

: 다음 XML 조각 주어진 예를 들어

,

abc 
def 

이 정확 ? 당신이 XSLT 코드를 (일부 필터 문제가) 해결하고 그것을 실행 한 경우

답변

6

가 아니, 당신은, 두 출력을하지 않습니다. 가능한 여러 템플릿이있는 경우 충돌 해결에 대한 규칙은 this page을 참조하십시오.

스타일 시트를 수정 한 후 (루벤스의 방식과 비슷하지만 모드는 동일 함) 일반적으로 xslt 파일의 마지막 템플릿이 적용되므로 결과물은 def이됩니다. 두 템플릿의 우선 순위가 같고 xslt 프로세서가 오류로 인해 멈추지 않으면 표준에서 마지막 템플릿을 적용해야합니다.

일치하는 템플릿 규칙이 두 개 이상있는 경우 오류가 발생합니다 . XSLT 프로세서가 오류를 알릴 수 있습니다. 오류를 알려주지 않으면 남아있는 일치하는 템플릿 규칙 중에서 스타일 시트에서 마지막으로 발생하는 규칙을 선택하여 복구해야합니다.

+0

+1, nice 대답 –

0

, 당신은 볼 수 : 데프

? <xsl:apply-templates />은 일치 조건을 충족하는 첫 번째 템플릿과 일치합니다. 두 개의 템플릿이있는 경우 <xsl:apply-templates>mode 속성이, 또는 <xsl:template>priority 속성을 사용하여 사용하여보다 다르게해야한다 : 하나의 템플릿이 선택 될 것이다

<xsl:stylesheet version="1.0" 
       xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

    <xsl:template match="/doc"> 
     <xsl:apply-templates select="foo" mode="2" /> 
    </xsl:template> 

    <xsl:template mode="1" match="foo[@bar='1']"> 
     abc 
    </xsl:template> 

    <xsl:template mode="2" match="foo[@baz='2']"> 
     def 
    </xsl:template> 

</xsl:stylesheet> 
4

당신은 는 그냥 속성을 선택하고 조건에 foo의 관계를 넣어 match XPATH를 조정해야합니다, 당신의 템플릿을 모두 속성 에 대한 일치시킬 않은 경우; (동일한 우선 순위를 가진) 동일한 특이성을 가진 foo요소에 일치하는 두 충돌 템플릿이 있어야합니다.

<?xml version="1.0" encoding="UTF-8"?> 
    <xsl:stylesheet 
    version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="xml" indent="yes" encoding="UTF-8"/> 

<xsl:template match="/"> 
    <xsl:apply-templates select="doc/foo" /> 
</xsl:template> 

<!--When templates match on foo, apply templates for it's attributes --> 
<xsl:template match="foo"> 
    <xsl:apply-templates select="@*"/> 
</xsl:template> 

<!--Unique template match for the bar attribute --> 
<xsl:template match="@bar[parent::foo and .='1']"> 
    abc 
</xsl:template> 

<!--Unique template match for the baz attribute --> 
<xsl:template match="@baz[parent::foo and .='2']"> 
    def 
</xsl:template> 

</xsl:stylesheet> 
+0

감사합니다. 불행히도 "왜"에 들어 가지 않으므로 대답을 받아 들일 수 없습니다. ;) –