2009-08-18 53 views
1

我在理解xslt時遇到了問題。在我的源文檔中,我必須找到<p>標記的內部文本,其中class屬性等於"deck"瞭解xslt處理具有屬性的元素

在我的源XML地方:

<body> 
    <p class="deck">Text here</p> 
... ... cut ... ... ... 

在我的XSL文件

<?xml version="1.0" encoding="utf-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:TimeInc="http://www.timeinc.com/namespaces/PAMTimeInc/1.0/" 
    xmlns:dc="http://purl.org/dc/elements/1.1/" 
    xmlns:prism="http://prismstandard.org/namespaces/basic/2.1/" 
    xmlns:pam="http://prismstandard.org/namespaces/pam/2.1/" 
    xmlns:pim="http://prismstandard.org/namespaces/pim/2.1/" 
    xmlns:prl="http://prismstandard.org/namespaces/prl/2.1/"> 

    <xsl:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="yes"/> 
    <Description> 
    <xsl:choose> 
     <xsl:when test="//[email protected] != ''"> 
     <xsl:value-of select="//[email protected]"/> 
     </xsl:when> 
     <xsl:otherwise> 
     <xsl:text disable-output-escaping="yes"/> 
     </xsl:otherwise> 
    </xsl:choose> 
    </Description> 
... ... cut ... ... ... 

它顯然是不正確,因爲我不知道我在做什麼。有沒有一個例子可以說明如何做到這一點或更多地理解它。

回答

2

我沒有看到任何地方作爲您的模板的基礎。不過,我認爲這是一個剪切和粘貼問題。

無論如何,一個XPath查找設置爲甲板類屬性的所有p元素是: // P [@類= '甲板']

你可以通過他們與迭代:

<xsl:for-each select="//p[@class='deck'"> 
</xsl:for-each> 
+1

非常感謝,最終代碼結束了: <的xsl:for-每個選擇= 「// P [@類= '甲板']」> stephenbayer 2009-08-18 20:44:44

2

你可以表達基於與屬性值的元素上的條件匹配,例如

element[@attribute = 'hello'] 

對於您的具體情況:

<p class="deck">Text here</p> 

嘗試:

//p[@class = 'deck']/text() 

這是一個XPath表達式,可以理解爲返回所有p元素的文本內容序列h值爲'deck'的屬性類。

XSLT使用XPath來導航XML文檔,所以它可能值得在XPath和XSLT上進行閱讀。

+0

我讀了W3Schools的權利,但我難以理解的語言和概念。他們的「嘗試」部分讓我獲得瞭解,但是通過做出改變並看到改變的作用。我正在閱讀XPath。 – stephenbayer 2009-08-18 21:06:23

2

嗯......像這樣的東西可能是:

<Description> 
    <xsl:choose> 
     <xsl:when test="//p[@class='deck']"> 
      <xsl:value-of select="//p[@class='deck']" /> 
     </xsl:when> 
     <xsl:otherwise> 
      <xsl:test> </xsl:text> 
     </xsl:otherwise> 
    </xsl:choose> 
</Description> 
相關問題