2012-01-31 2 views
1

나는이 나무/하나/차/차와 두 번째/메이커/자동차/차를 가진 나무를 가지고있다. 첫번째 것은 차의 두 번째 목록의 id에 대한 참조를 가지고있다. 두 요소가 xslt에서 같은 이름을 가질 때 어떻게 서로 연결합니까?

내가 이것을 가지고

<xsl:template match="t:cars/t:car"> 
<tr> 
    <td> 
     <xsl:if test="position()=1"> 
      <b><xsl:value-of select="../@name"/><xsl:text> </xsl:text></b> 
     </xsl:if> 


    </td> 
</tr> 

, 그것은 내가 그것을 할 could't 조금 후에 배울 for 루프에 가득 차 있었다.

은 무엇인지하기 전에 :

<xsl:template match="t:cars/t:car"> 
<tr> 
    <td> 
     <xsl:if test="position()=1"> 
      <b><xsl:value-of select="../@name"/><xsl:text> </xsl:text></b> 
     </xsl:if> 
     <xsl:for-each select="/t:root/t:maker/t:car"> 
      <xsl:if test="t:root/t:maker/@id = @ref"> 
       <xsl:value-of select="@title"/> 
      </xsl:if> 
     </xsl:for-each> 

    </td> 
</tr> 

샘플 :

auto> 
<maker type="toyota"> 
    <car name="prius" id="1"/> 
</maker> 

<cars name="My Collection"> 
    <car ref="1" /> 
</cars> 

+0

샘플 입력 및 필수 출력 xml을 사용하면 문제를 훨씬 쉽게 이해할 수 있습니다. – Kevan

답변

1

이 간단한 변환 :

이 XML 문서에 적용
<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 
<xsl:strip-space elements="*"/> 

<xsl:key name="kCarById" match="maker/car" use="@id"/> 

<xsl:template match="/*"> 
    <table> 
    <xsl:apply-templates/> 
    </table> 
</xsl:template> 

<xsl:template match="cars/car"> 
    <tr> 
     <td> 
      <b> 
      <xsl:value-of select="key('kCarById', @ref)/@name"/> 
      </b> 
     </td> 
    </tr> 
</xsl:template> 
</xsl:stylesheet> 

(하나의 제공은, 조금 확장) :

<auto> 
    <maker type="toyota"> 
     <car name="prius" id="1"/> 
    </maker> 
    <maker type="honda"> 
     <car name="accord" id="2"/> 
    </maker> 
    <maker type="benz"> 
     <car name="mercedes" id="3"/> 
    </maker> 

    <cars name="My Collection"> 
     <car ref="2" /> 
     <car ref="3" /> 
    </cars> 
</auto> 

가 원하는, 올바른 결과 생산 :

<table> 
    <tr> 
     <td> 
     <b>accord</b> 
     </td> 
    </tr> 
    <tr> 
     <td> 
     <b>mercedes</b> 
     </td> 
    </tr> 
</table> 

설명을 : keys의 적절한 사용.

관련 문제