2017-01-11 40 views
2

我是XSL的新手。我想從我的HTML中提取兩個值(標題和說明)。這是我的HTML看起來像如何使用XSL從html中提取標題和描述等元數據

... 
    tbody id="_tableBody"> 
    <tr id="tcm:526-94999" class="alt-rowcolor" style="display: table-row;"> 
    <th class="heading" scope="row" style="display: table-cell;"> 
    <a onclick="displayAgreementPDFPopIn('202', 'ddctable-526-93813', 'Link_1382596320857', '540', 'false')" href="javascript:void(0)">529 Plan – Investment Instructions</a> 
    </th> 
    <td class="description" style="display: table-cell;">Change how your future contributions are invested or make an exchange of the contributions and earnings currently invested in your 529 college savings plan.</td> 
    </tr> 
... 

對於如我想

<title> 529 Plan – Investment Instructions</title> 
<description> Change how your future contributions are invested or make an exchange of the contributions and earnings currently invested in your 529 college savings plan </description> 

這是元素的XPATH:

/html/body/div[2]/div[4]/div[4]/table/tbody/ 

我下的所有其他標題和描述這條道路。我爲這個轉換創建了下面的XSL。

<xsl:template match="/"> 
    <xsl:apply-templates select="/html/body/div[2]/div[4]/div[4]/table/tbody" /> 
</xsl:template> 
<xsl:template match="tbody"> 
    <xsl:call-template name="PDF_metadata"> 
     </xsl:call-template> 
</xsl:template> 
<xsl:template name="PDF_metadata"> 
    <xsl:variable name="title" select="/tr/th/a"> 
    <xsl:variable name="description" select="/tr/th/td"/> 
    <xsl:attribute name="title"> 
     <xsl:value-of select="$title" /> 
    </xsl:attribute> 
    <xsl:attribute name="description"> 
     <xsl:value-of select="$description" /> 
</xsl:template> 

這是使用XSL的正確方法嗎?我做對了嗎?任何幫助,將不勝感激。

回答

1

我覺得你太複雜了你的最後一個模板。未經檢驗的,但我認爲這是更接近你想要的東西:

<xsl:template name="PDF_metadata"> 
    <title> 
    <xsl:value-of select="tr/th/a" /> 
    </title> 
    <description> 
    <xsl:value-of select="tr/td" /> 
    </description> 
</xsl:template> 

更新

與在線XSLT儀玩耍了。這應該適合你;它用一個簡單的替換所有3個模板。

<xsl:template match="//tbody[@id='_tableBody']"> 
    <title> 
    <xsl:value-of select="tr/th/a" /> 
    </title> 
    <description> 
    <xsl:value-of select="tr/td" /> 
    </description> 
</xsl:template> 

說明:

//tbody發現根節點以下任何<tbody/>節點。不要緊它是如何深度嵌套的,或者是在什麼位置內<div/>標籤等,但也可以是那些不止一個,所以......

//tbody[@id='_tableBody'] ......只有符合<tbody/>與屬性id='_tableBody'。由於id屬性必須是唯一的,因此只能有一個。

<xsl:value-of select="..." />中,我們已經在<tbody/>節點。要獲得標題,我們不希望從當前節點(<tbody/>節點)使用tr/th/a(請注意在開始時缺少/)的文檔根目錄中搜索/tr/th/a。說明同上。

+0

謝謝你的回答。我有一個很大的html文件,它有很多tr和td標籤。我想我必須指定整個路徑/ html/body/div [2]/div [4]/div [4]/table/tbody /才能到達該元素。你怎麼看? – Rose

+0

@NupurJaiswal更新。由於'tbody'標籤具有'id'屬性,因此可以將標籤的搜索從'/ html/body/div [2]/div [4]/div [4]/table/tbody'大大簡化爲' // tbody [@id ='_ tableBody']' – AJNeufeld

+0

太好了。非常感謝。我會檢查這個答案 – Rose

相關問題