Simpelt eksempel:
using System;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.Serialization;
namespace E
{
public class Data
{
private int iv;
private string sv;
public Data() : this(0, "")
{
}
public Data(int iv, string sv)
{
this.iv = iv;
this.sv = sv;
}
public int Iv
{
get { return iv; }
set { iv = value; }
}
public string Sv
{
get { return sv; }
set { sv = value; }
}
}
public class Program
{
public static string Object2Xml(object o)
{
XmlSerializer ser = new XmlSerializer(o.GetType());
StringWriter sw = new StringWriter();
ser.Serialize(sw, o);
return sw.ToString();
}
public static string Xml2Html(string xml, string xsl)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(new XmlTextReader(new StringReader(xsl)), null, null);
StringWriter sw = new StringWriter();
XmlTextWriter wrt = new XmlTextWriter(sw);
wrt.Formatting = Formatting.Indented;
xslt.Transform(doc, wrt);
return sw.ToString();
}
public static void Main(string[] args)
{
string dataxsl = @"<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl='
http://www.w3.org/1999/XSL/Transform' version='1.0'>
<xsl:template match='/Data'>
<a>
<xsl:attribute name='href'><xsl:value-of select='Sv'/></xsl:attribute>
<xsl:value-of select='Iv'/>
</a>
</xsl:template>
</xsl:stylesheet>";
Data o = new Data(123, "page123.html");
string xml = Object2Xml(o);
Console.WriteLine(xml);
string html = Xml2Html(xml, dataxsl);
Console.WriteLine(html);
Console.ReadKey();
}
}
}