2017-04-03 19 views
0

我一直在嘗試爲此獲取解決方案,但仍無法找到適當的解決方案。 我參考了幾個鏈接Nested for-each loops, accessing outer element with variable from the inner loopHow to extract child tags text and extended text of parent tag from xml using xslt但這些問題沒有嵌套標籤。XSLT:如何根據依賴於其子標記的值的條件獲取父標記的值,並使用高度嵌套的XML

我的XML:

<catalog title="TitleABC1"> 
    <cd> 
    <title code="Y">Picture book</title> 
    <artist>Simply Red</artist> 
    <country>EU</country> 
    </cd> 
    <catalog title="TitleABC2"> 
    <cd> 
     <cd> 
     <title code="N">Empire Burlesque</title> 
     <artist>Bob Dylan</artist> 
     <country>USA</country> 
     </cd> 
    </cd> 
    <cd> 
     <cd> 
     <cd> 
      <title code="Y">Hide your heart</title> 
      <artist>Bonnie Tyler</artist> 
      <country>UK</country> 
     </cd> 
     </cd> 
    </cd> 
    <cd> 
     <catalog title="TitleABC3"> 
     <cd> 
      <title code="N">Red</title> 
      <artist>The Communards</artist> 
      <country>UK</country> 
     </cd> 
     </catalog> 
    </cd> 
    <cd> 
     <title code="N">Unchain my heart</title> 
     <artist>Joe Cocker</artist> 
     <country>USA</country> 
    </cd> 
    </catalog> 
</catalog> 

對於上面的XML,條件是,只有那些catalog標籤的標題會如果有孩子/後裔title標籤具有代碼屬性爲「Y」來顯示。

因此,輸出應該是這樣的:

TitleABC1 
TitleABC2 

我試圖在以下邏輯XSLT,但無法獲得所需的解決方案。

<xsl:template match="catalog"> 
<!-- Store the value in a variable --> 
       <xsl:for-each select="//title"> 
<!-- <xsl:if> to check for the code attrib -->             
       </xsl:for-each> 
      </xsl:template> 
+0

由於您是通過解釋您如何找到答案來解答問題的,請讓我評論一下您的問題解決策略。在網絡上搜索與您的英文語言描述相匹配的現有代碼是不太可能的:這有點像搜索「添加3到17」,這將無法找到成功添加4到18的代碼。這將是更好地投入精力來理解語言的基本操作,例如路徑表達式,座標軸和過濾器表達式,並學習如何自己組合它們。 –

+0

是@MichaelKay,你是對的。我不知道路徑表達式,軸。當然,我會更多地考慮這些主題並研究它們。 – CuE

回答

1

僅如果任何 子/後代title標籤具有代碼屬性爲「Y」的catalog標籤將被顯示。

你爲什麼不做的正是你所說的做需求:

XSLT 1.0

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

<xsl:template match="/"> 
    <xsl:for-each select="//catalog[descendant::title/@code='Y']"> 
     <xsl:value-of select="@title" /> 
     <xsl:text>&#10;</xsl:text> 
    </xsl:for-each> 
</xsl:template> 

</xsl:stylesheet> 

或者,如果你喜歡一個遞歸方法:

XSLT 1.0

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

<xsl:template match="catalog[descendant::title/@code='Y']"> 
    <xsl:value-of select="@title" /> 
    <xsl:text>&#10;</xsl:text> 
    <xsl:apply-templates select="*"/> 
</xsl:template> 

<xsl:template match="text()"/> 

</xsl:stylesheet> 

您需要了解有關built-in template rules以瞭解其工作原理。

+0

謝謝@ michael.hor257k。我花了一些時間來了解解決方案,並正確地達到了目的。再次感謝。 – CuE