如何使用XSLT从xml检索数据时将属性添加到每个标记

时间:2012-05-04 13:22:10

标签: xslt

我有xml文件,如下所示:

    <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE pointList SYSTEM "point.dtd">
<pointList>
<point unit="mm">
<x>2</x>
<y>3</y>
</point>
<point unit="cm">
<x>9</x>
<y>3</y>
</point>
<point unit="px">
<x>4</x>
<y>7</y>
</point>
</pointList>

使用XSLT我将其转换为html文件:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>

    <xsl:template match = "/pointList">
    <table border = "1"><xsl:apply-templates/></table>
    </xsl:template>
    <xsl:template match = "/pointList/point">
    <tr><xsl:apply-templates/></tr>
    </xsl:template>
    <xsl:template match="pointList/point/x">
    <td><xsl:value-of select="text()"/></td>
    </xsl:template>
    <xsl:template match="pointList/point/y">
    <td><xsl:value-of select="text()"/></td>
    </xsl:template>

</xsl:stylesheet> 

现在我的html看起来像这样:

<table border="1">

<tr>

<td>2</td>
<td>3</td>

</tr>

<tr>

<td>9</td>
<td>3</td>

</tr>

<tr>

<td>4</td>
<td>7</td>

</tr>

</table>

但我还有一件事要做,我被困住了。我的xml文件中有unit属性。我必须将单位的值添加到每个点,所以它看起来像这样:2毫米3毫米 9厘米3厘米 4px 7像素。任何人都可以告诉我如何修改我的xslt文件,以便我得到我想要的东西? 感谢

1 个答案:

答案 0 :(得分:3)

更改

<xsl:template match="pointList/point/x">
  <td><xsl:value-of select="text()"/></td>
</xsl:template>

<xsl:template match="pointList/point/y">
  <td><xsl:value-of select="text()"/></td>
</xsl:template>

<xsl:template match="pointList/point/*">
  <td><xsl:value-of select="concat(text(), ../@unit)"/></td>
</xsl:template>