尽管在各种网站上阅读了大量有关 XSLT 模板的文档,但我无法让 XSLT 与我的 C# 代码一起工作。
这是我的工作 XSLT 文件:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<HTML>
<BODY>
<TABLE BORDER="2">
<TR>
<TD>First name</TD>
<TD>Last name</TD>
<TD>Age</TD>
</TR>
<xsl:for-each select="ArrayOfUserModel/UserModel">
<TR>
<TD><xsl:value-of select="FirstName"/></TD>
<TD><xsl:value-of select="LastName"/></TD>
<TD><xsl:value-of select="Age"/></TD>
</TR>
</xsl:for-each>
</TABLE>
</BODY>
</HTML>
</xsl:template>
</xsl:stylesheet>
这是我的非工作 XSLT 文件(和处理已移至样式表末尾的模板,理论上应该返回相同但不显示任何用户信息):
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<HTML>
<BODY>
<TABLE BORDER="2">
<TR>
<TD>First name</TD>
<TD>Last name</TD>
<TD>Age</TD>
</TR>
<xsl:for-each select="ArrayOfUserModel/UserModel">
<xsl:apply-templates select="user"/>
</xsl:for-each>
</TABLE>
</BODY>
</HTML>
</xsl:template>
<xsl:template match="user">
<TR>
<TD><xsl:value-of select="FirstName"/></TD>
<TD><xsl:value-of select="LastName"/></TD>
<TD><xsl:value-of select="Age"/></TD>
</TR>
</xsl:template>
</xsl:stylesheet>
这里是我用于 XSLT 转换的 C# 代码:(我传递了一个可序列化的 UserModel 对象,其中包含一些属性和 XSLT 文件的内容,然后它返回 HTML)
public static string TransformXml2(object data, string xslt)
{
XmlSerializer xs = new XmlSerializer(data.GetType());
string xml;
using (StringWriter swr = new StringWriter())
{
xs.Serialize(swr, data);
xml = swr.ToString();
}
// Simple data checks
if (string.IsNullOrEmpty(xml))
{
throw new ArgumentException("Param cannot be null or empty", "xml");
}
if (string.IsNullOrEmpty(xslt))
{
throw new ArgumentException("Param cannot be null or empty", "xslt");
}
// Create required readers for working with xml and xslt
StringReader xsltInput = new StringReader(xslt);
StringReader xmlInput = new StringReader(xml);
XmlTextReader xsltReader = new XmlTextReader(xsltInput);
XmlTextReader xmlReader = new XmlTextReader(xmlInput);
// Create required writer for output
StringWriter stringWriter = new StringWriter();
XmlTextWriter transformedXml = new XmlTextWriter(stringWriter);
// Create a XslCompiledTransform to perform transformation
XslCompiledTransform xsltTransform = new XslCompiledTransform();
try
{
xsltTransform.Load(xsltReader, new XsltSettings(true, true), null);
xsltTransform.Transform(xmlReader, transformedXml);
}
catch (XmlException xmlEx)
{
// TODO : log - "Could not load XSL transform: \n\n" + xmlEx.Message
throw;
}
catch (XsltException xsltEx)
{
// TODO : log - "Could not process the XSL: \n\n" + xsltEx.Message + "\nOn line " + xsltEx.LineNumber + " @ " + xsltEx.LinePosition)
throw;
}
catch (Exception ex)
{
// TODO : log
throw;
}
return stringWriter.ToString();
}
非常感谢 !