2017-01-14 67 views
0

我想下面的代碼轉換成3個表:在桌組特定元素使用XSLT 1.0

<bold>Hello</bold> 
<bold>world</bold> 
<p>Hello world!</p> 
<bold>Please</bold> 
<bold>help</bold> 
<bold>me</bold> 
<p>Please help me.</p> 
<h1>This community is great<h1> 
<bold>Thank</bold> 
<bold>you</bold> 
<bold>very</bold> 
<bold>much</bold> 

最後的結果應該是這樣的:

<table> 
<th>NewHeader1<th> 
<tr> 
<td>Hello</td> 
<td>world</td> 
</tr> 
</table> 
<p>Hello world!</p> 

<table> 
<th>NewHeader2<th> 
<tr> 
<td>Please</td> 
<td>help</td> 
<td>me</td> 
</tr> 
</table> 
<p>Please help me.</p> 
<h1>This community is great.<h1> 

<table> 
<th>NewHeader3<th> 
<tr> 
<td>Thank</td> 
<td>you</td> 
<td>very</td> 
<td>much</td> 
</tr> 
</table> 

不幸的是,我只做到將所有粗體元素放在一張表中。謝謝你的幫助!

+0

請發表您的嘗試,所以我們可以解決,而不必從頭開始編寫代碼爲你它。 –

回答

2

給定一個合式 XML輸入如:

XML

<root> 
    <bold>Hello</bold> 
    <bold>world</bold> 
    <p>Hello world!</p> 
    <bold>Please</bold> 
    <bold>help</bold> 
    <bold>me</bold> 
    <p>Please help me.</p> 
    <h1>This community is great</h1> 
    <bold>Thank</bold> 
    <bold>you</bold> 
    <bold>very</bold> 
    <bold>much</bold> 
</root> 

可以使用稱爲同級遞歸的技術:

XSLT 1.0

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

<!-- identity transform --> 
<xsl:template match="@*|node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="bold"> 
    <table> 
     <th> 
      <xsl:text>NewHeader</xsl:text> 
      <xsl:number count="bold[not(preceding-sibling::*[1][self::bold])]"/> 
     </th> 
     <tr> 
      <xsl:apply-templates select="." mode="cell"/>   
     </tr> 
    </table> 
</xsl:template> 

<xsl:template match="bold" mode="cell"> 
    <td> 
     <xsl:value-of select="."/> 
    </td> 
    <!-- sibling recursion --> 
    <xsl:apply-templates select="following-sibling::*[1][self::bold]" mode="cell"/>   
</xsl:template> 

<xsl:template match="bold[preceding-sibling::*[1][self::bold]]"/> 

</xsl:stylesheet> 

產生:

結果

<?xml version="1.0" encoding="UTF-8"?> 
<root> 
    <table> 
     <th>NewHeader1</th> 
     <tr> 
     <td>Hello</td> 
     <td>world</td> 
     </tr> 
    </table> 
    <p>Hello world!</p> 
    <table> 
     <th>NewHeader2</th> 
     <tr> 
     <td>Please</td> 
     <td>help</td> 
     <td>me</td> 
     </tr> 
    </table> 
    <p>Please help me.</p> 
    <h1>This community is great</h1> 
    <table> 
     <th>NewHeader3</th> 
     <tr> 
     <td>Thank</td> 
     <td>you</td> 
     <td>very</td> 
     <td>much</td> 
     </tr> 
    </table> 
</root> 
+0

非常感謝邁克爾!對不起,我還是很新的,有時候我會忘記通過發佈我的代碼來讓幫手的生活更輕鬆。老實說,它完全不同。非常感謝你! – Gnarlund