[英]Use XSL to parse XML "color" attribute to fill a table cell
我正在學習 XML,但遇到了以下問題:我的 XML 文件中有一個屬性可以將顏色作為內容(例如<color>red</color>
),但我不知道如何用它。
我的 XML:
<?xml version="1.0" encoding="UTF-8"?>
<cars>
<car year="2002" manufacturer="Jet" model="Sardine Can 1.6L">
<meter>95664</meter>
<color>silver</color>
<price>099900</price>
<dealersecurity buyback="no"/>
</car>
<car year="2004" manufacturer="Jet" model="Sardine Can 2.0">
<meter>81283</meter>
<color>red</color>
<price>129900</price>
<dealersecurity buyback="no"/>
</car>
<car year="2007" manufacturer="Jet" model="Sardine Can 2.0">
<meter>49741</meter>
<color>black</color>
<price>169999</price>
<dealersecurity buyback="yes"/>
</car>
</cars>
我的 XSL:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml"
version="1.0">
<xsl:output method="xml"/>
<xsl:template match="/cars">
<html>
<head><title>Second Hand Sardine Cans</title>
<link rel="stylesheet" type="text/css" href="style.css"/></head>
<body>
<h1>Second Hand Sardine Cans</h1>
<table border="1"><th>Make</th><th>Model</th><th>Year</th><th>KMs</th><th>Color</th><th>Price</th><th>Warranty</th><xsl:apply-templates/></table>
</body>
</html>
</xsl:template>
<xsl:template match="cars/car">
<tr><xsl:for-each select="cars/car"/>
<td><xsl:value-of select="@manufacturer" /></td>
<td><xsl:value-of select="@model" /></td>
<td><xsl:value-of select="@year" /></td>
<td><xsl:value-of select="meter" /></td>
<xsl:apply-templates/></tr>
</xsl:template>
<xsl:template match="meter"/>
<xsl:template match="color">
<td><xsl:apply-templates /></td>
</xsl:template>
<xsl:template match="price">
<td><xsl:apply-templates /></td>
</xsl:template>
</xsl:stylesheet>
到目前為止我所擁有的:
但不是說“紅色”或“黑色”,我希望該單元格填充准確的顏色。
謝謝!
編輯:我在 Dimitre 的回答的幫助下修復了它。 我在<td><xsl:value-of select="meter" /></td>
下面添加了<td bgcolor="{color}"><xsl:value-of select="color" /></td>
<td><xsl:value-of select="meter" /></td>
只是改變你的轉變:
<tr>
到:
<tr bgcolor="{color}">
或者,如果您真的只想擁有一個具有該顏色的單元格,請在與color
匹配的模板中使用:
<td bgcolor="{.}">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.