cs(c#):
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Text;
protected void Page_Load(object sender, EventArgs e)
{
XmlReader xmlreader = XmlReader.Create(Server.MapPath("htmlxml/books.xml"));
XmlReader xsltreader = XmlReader.Create(Server.MapPath("htmlxml/books.xslt"));
StringBuilder sb = new StringBuilder();
try
{
XslCompiledTransform xlst = new XslCompiledTransform();
xlst.Load( xsltreader);
XPathDocument doc = new XPathDocument(xmlreader);
System.IO.StringWriter sw = new System.IO.StringWriter(sb);
XmlTextWriter writer = new XmlTextWriter(sw);
xlst.Transform(doc, writer);
writer.Close();
Response.Write(sb.ToString());
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
结果:
My CD Collection
name | publisher |
---|---|
Xml初学 | 人民出版社 |
XSD定义 | 子弟出版社 |
xml:
<?xml version="1.0" encoding="utf-8" ?>
<!--<?xml-stylesheet type="text/xsl" href="books.xslt"?>-->
<library>
<name>首都图书馆</name>
<address>朝阳区华威桥南</address>
<books>
<book type="math">
<id>0000</id>
</book>
<book type="computer">
<id>0001</id>
<name>Xml初学</name>
<publisher>人民出版社</publisher>
<fee>100.54</fee>
</book>
<book type="computer">
<id>0002</id>
<name>XSD定义</name>
<author>子弟</author>
<publisher>子弟出版社</publisher>
<publishdate>2010-05-0-18</publishdate>
<fee>102.54</fee>
</book>
</books>
</library>
xsl:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:template match="/">
<html>
<body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="books">
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th align="left">name</th>
<th align="left">publisher</th>
</tr>
<xsl:apply-templates select="book"/>
</table>
</xsl:template>
<xsl:template match="book">
<xsl:if test="@type='computer'">
<xsl:choose>
<xsl:when test="publisher='人民出版社'">
<tr>
<td>
<xsl:value-of select="name"/>
</td>
<td bgcolor="#18b828">
<xsl:value-of select="publisher"/>
</td>
</tr>
</xsl:when>
<xsl:otherwise>
<tr>
<td>
<xsl:value-of select="name"/>
</td>
<td bgcolor="aaaaaa">
<xsl:value-of select="publisher"/>
</td>
</tr>
</xsl:otherwise>
</xsl:choose>
</xsl:if>
</xsl:template>
</xsl:stylesheet>