Passing XML Attribute value to HTML Atrribute valu

2019-08-10 22:50发布

I have an XML file with certain data which I have to convert it into HTML Table. There are 3-4 table with only 2 columns and 4-5 tables with more columns. I want to pass XML attribute value, say tableWidth=200 or tableWidth=500 depending upon the number of columns.

Sample XML File -

<tab>
  <!-- b="Y" will be used if Heading is required -->
  <r b="Y">
    <d>Name</d>
    <d>Age</d>
  </r>
  <r>
    <d>ABC</d>
    <d>23</d>
  </r>
</tab>

Following is the XSLT File -

<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:output method='html' media-type='text/html'/>
<xsl:template match="Tab">
<table width="500" cellpadding="6" cellspacing="0" align="center">
  <xsl:for-each select="R">
<tr>
    <xsl:choose>
        <xsl:when test="@b = 'Y'">
            <xsl:for-each select="D">
                <td align='' style='border:1px solid black'> 
                    <b><xsl:value-of select="."/></b>
                </td>
            </xsl:for-each>
        </xsl:when>
        <xsl:otherwise>
            <xsl:for-each select="D">
                <td align='' style='border:1px solid black'> 
                    <xsl:value-of select="."/>  
                </td>
            </xsl:for-each>
        </xsl:otherwise>
    </xsl:choose>
</tr>
  </xsl:for-each>
 </table>
 </xsl:template>
 </xsl:stylesheet>   

I want to add an attribute say tablewidth to XML file and use it in the <table> tag is XSLT file...

标签: html xml xslt
1条回答
手持菜刀,她持情操
2楼-- · 2019-08-10 23:02

Assuming you have amended your XML to include an tableWidth attribute, like so...

<tab tableWidth="500">
    ....

There are two ways to make use of the attribute in the XSLT. Firstly, the more verbose way....

<xsl:template match="Tab">
   <table cellpadding="6" cellspacing="0" align="center"> 
      <xsl:attribute name="width"><xsl:value-of select="@tableWidth" /></xsl:attribute>

But it is often much cleaner to use Attribute Value Templates. Then you only have to do this:

<xsl:template match="Tab">
   <table width="{@tableWidth}" cellpadding="6" cellspacing="0" align="center"> 

Both of these should output the following:

<table width="500" cellpadding="6" cellspacing="0" align="center">
查看更多
登录 后发表回答