2014-06-24 47 views
-1

我需要使用XSLTProcessor将xml文档转换为html。如何使用XSL将XML转换为HTML?

我的XML文件是:

<?xml version="1.0" encoding="utf-8"?> 
<items> 
    <item> 
     <property title="title1"><![CDATA[data1]]></property> 
     <property title="title2"><![CDATA[data3]]></property> 
     <property title="title3"><![CDATA[data3]]></property> 
     </item> 
     <item> 
     <property title="title4"><![CDATA[data4]]></property> 
     <property title="title5"><![CDATA[data5]]></property> 
     <property title="title6"><![CDATA[data6]]></property> 
     </item> 
</items> 

我要得到的是:

<html> 
    <table border="1"> 
     <tr bgcolor="#eee"><td colspan="2">title1: data1</td></tr> 
       <tr><td> title2</td> <td>data2</td></tr> 
     <tr><td> title3</td> <td>data3</td></tr> 

     <tr bgcolor="#eee"><td colspan="2">title4: data4</td></tr> 
       <tr><td> title5</td> <td>data5</td></tr> 
     <tr><td> title6</td> <td>data6</td></tr> 


    </table> 
</html> 

我的XSL文件现在是:

<?xml version="1.0" encoding="utf-8"?> 
<xsl:stylesheet version="1.0" 
xmlns:php="http://php.net/xsl" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

<xsl:output method="html" encoding="UTF-8" indent="yes"/> 

    <xsl:template match="/"> 
    <html> 
     <xsl:apply-templates select="items"/> 
    </html> 
    </xsl:template> 

    <xsl:template match="items"> 
    <table border="1"> 
     <xsl:apply-templates select="item"/> 
     </table> 
    </xsl:template> 

    <xsl:template match="item"> 

    <tr bgcolor="#eee"> <td colspan="2"> 
     <xsl:value-of select="/descendant::*/@*"/>: 
     <xsl:value-of select="property"/> 
     </td> </tr> 

    </xsl:template> 
</xsl:stylesheet> 

但只返回第一个标签“属性”。我是xslt中的新成员,我该如何获取“property”标记列表?

回答

1

您使用范本罚款之初,就继续这样做,写作模板和应用它们:

<xsl:stylesheet version="1.0" 

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

<xsl:output method="html" encoding="UTF-8" indent="yes"/> 

    <xsl:template match="/"> 
    <html> 
     <xsl:apply-templates select="items"/> 
    </html> 
    </xsl:template> 

    <xsl:template match="items"> 
    <table border="1"> 
     <xsl:apply-templates/> 
     </table> 
    </xsl:template> 

    <xsl:template match="item/property[1]"> 

    <tr bgcolor="#eee"> <td colspan="2"> 
     <xsl:value-of select="@title"/>: 
     <xsl:value-of select="."/> 
     </td> </tr> 

    </xsl:template> 

    <xsl:template match="item/property[not(position() = 1)]"> 
     <tr> 
     <td><xsl:value-of select="@title"/></td> 
     <td><xsl:value-of select="."/></td> 
     </tr> 
    </xsl:template> 
</xsl:stylesheet> 
+0

谢谢,它的工作原理!) –

0

您需要使用for-each声明

<xsl:template match="item"> 
    <xsl:for-each select = "property"> 
    <tr bgcolor="#eee"> 
     <td colspan="2"> 
     <xsl:value-of select="/descendant-or-self::*/@*"/>: 
     <xsl:value-of select="."/> 
     </td> 
    </tr> 
    </xsl:for-each> 
</xsl:template> 

我也改变了你的descendantdescendant-or-self是完全等同于你有什么之前。

+0

谢谢,它的工作原理也一样,但用“的