今天笔试时关于xsl控制xml显示的一道题 请大家帮忙
问题:
<department name=”dept1”> </department>
<department name=”dept2”> </department>
<department name=”dept3>
<user name=”user1”> </user>
<user name=”user2”> </user>
</department>
使用xsl实现下列显示
Department: dept1
Department: dept2
Department: dept3
User: user1
User: user2
我写的是
<?xml version= "1.0 "?>
<xsl:stylesheet xmlns:xsl= "http://www.w3.org/TR/WD-xsl ">
<xsl:template match= "/ ">
<xsl:for-each select= "company/department ">
Department: <xsl:value-of select= "@name "/>
<br/>
User: <xsl:value-of select= "user/@name "/>
<br/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
结果不对 有的节点有user 有的没有 我不知道要怎么处理 还有怎么样把 <tag> 的名字选出来..请大家帮忙
[解决办法]
<xsl:for-each select= "company/department ">
Department: <xsl:value-of select= "@name "/>
<br/>
<xsl:for-each select= "user ">
User: <xsl:value-of select= "@name "/>
<br/>
</xsl:for-each>
</xsl:for-each>
[解决办法]
<?xml version= "1.0 "?>
<xsl:stylesheet version= "1.0 " xmlns:xsl= "http://www.w3.org/1999/XSL/Transform ">
<xsl:template match= "*[@name] ">
<xsl:value-of select= "concat(translate(name(), 'du ', 'DU '), ': ',@name) "/>
<br/>
<xsl:apply-templates select= "* "/>
</xsl:template>
</xsl:stylesheet>
还要注意User的缩近的话,要复杂些。
[解决办法]
test.xml
<?xml version= "1.0 " encoding= "gb2312 "?>
<?xml-stylesheet type= "text/xsl " href= "test.xsl "?>
<company>
<department name= "dep1 "> </department>
<department name= "dep2 "> </department>
<department name= "dep3 ">
<user name= "user1 "> </user>
<user name= "user2 "> </user>
</department>
</company>
//========================================================
test.xsl
<?xml version= "1.0 " encoding= "gb2312 "?>
<xsl:stylesheet version= "1.0 " xmlns:xsl= "http://www.w3.org/1999/XSL/Transform ">
<xsl:template match= "/ ">
<html xmlns= "http://www.w3.org/1999/xhtml ">
<head>
<title> yours </title>
</head>
<body>
<table border= "0 " >
<xsl:for-each select= "company/department ">
<tr>
<td bgcolor= "#FF9900 "> Department: </td>
<td> <xsl:value-of select= "@name "/> </td>
</tr>
</xsl:for-each>
<xsl:for-each select= "company/department/user ">
<tr>
<td align= "right "> user: </td>
<td> <xsl:value-of select= "@name "/> </td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
//===========================================================
user的格式其实就是居右!
[解决办法]
<xsl:stylesheet version= "1.0 " xmlns:xsl= "http://www.w3.org/1999/XSL/Transform ">
<xsl:output method= "html " />
<xsl:template match= "/ ">
<xsl:apply-templates />
</xsl:template>
<xsl:template match= "department ">
<dl style= "margin:0; padding:0; ">
<dd> Department: <xsl:value-of select= "@name " /> </dd>
<xsl:apply-templates /> </dl>
</xsl:template>
<xsl:template match= "user ">
<dl>
<dd> User: <xsl:value-of select= "@name " /> </dd>
<xsl:apply-templates />
</dl>
</xsl:template>
</xsl:stylesheet>