2011-09-20 113 views
4

我有大量的XML文件:生成HTML形式動態地使用XML和XSLT可重用

第一:

<xmldata1> 
    <record> 
     <property11>abc</property11> 
     <property12>def</property12> 
     <property13>xyz</property13> 
     ............ 
    </record> 
    ........ 
</xmldata1> 

二:

<xmldata2> 
    <record> 
     <property21>abc</property21> 
     <property22>def</property22> 
     <property23>xyz</property23> 
     ............ 
    </record> 
    ........ 
</xmldata2> 

等。

不會有任何更多的嵌套標籤。 但是,每個xmldata文件的屬性標籤的名稱都會有所不同。

所以我想動態生成一個HTML表格使用XSLT來讀取每個xml的數據。如果應該使用簡單的文本框來讀取每個屬性。我們可以將第一條記錄作爲參考數字和名稱的屬性。

所需的輸出

<form name ="xmldata1"> 
    <table> 
     <tr> 
      <td>property11 :</td> 
      <td><input type="text" name="property11"></td> 
     </tr> 
     ....... 
     and so on 
    </table> 
</form> 

我怎樣才能做到這一點。我在哪裏可以找到此示例。

+0

將是很好的提供你嘗試什麼,沒想到社區寫這個給你一個例子,不是堆棧溢出的目的。 – Kev

回答

5
<?xml version="1.0"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="html" indent="yes" /> 

    <!--Template match for the document element, no matter what the name --> 
    <xsl:template match="/*"> 
     <form name="{local-name()}"> 
     <table> 
      <!--Apply-templates for all of the record/property elements --> 
      <xsl:apply-templates select="*/*"/> 
     </table> 
     </form> 
    </xsl:template> 

    <!--Match on all of the property elements and create a new row for each --> 
    <xsl:template match="/*/*/*"> 
     <tr> 
     <td><xsl:value-of select="local-name()"/> :</td> 
     <td><input type="text" name="{local-name()}"/></td> 
     </tr> 
    </xsl:template> 

</xsl:stylesheet> 
+0

正是我想要的。 – gtiwari333

3

你的意思是這樣嗎?

<?xml version="1.0" encoding="ISO-8859-1"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 

<xsl:output method="html" /> 

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

<xsl:template match="*[starts-with(name(), 'xmldata')]"> 
    <xsl:element name="form"> 
     <xsl:attribute name="name"><xsl:value-of select="name(.)" /></xsl:attribute> 
     <table> 
      <tr> 
       <xsl:apply-templates /> 
      </tr> 
     </table> 
    </xsl:element> 
</xsl:template> 

<xsl:template match="record"> 
    <xsl:apply-templates /> 
</xsl:template> 

<xsl:template match="*[starts-with(name(), 'property')]"> 
    <td> 
     <xsl:value-of select="name(.)" /> 
    </td> 
    <td> 
     <xsl:element name="input"> 
      <xsl:attribute name="type">text</xsl:attribute> 
      <xsl:attribute name="name"><xsl:value-of select="name(.)" /></xsl:attribute> 
     </xsl:element> 
    </td> 
</xsl:template>