Endnu en gang XSL:
using System;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.Serialization;
public class C3
{
public string f1;
public string f2;
public string f3;
}
class MainClass
{
private static void standard(C3 c3)
{
Console.WriteLine("Standard:");
XmlSerializer ser = new XmlSerializer(typeof(C3));
ser.Serialize(Console.Out, c3);
Console.WriteLine();
}
private static void transformed(C3 c3)
{
Console.WriteLine("Transformed:");
XmlSerializer ser = new XmlSerializer(typeof(C3));
StringWriter sw = new StringWriter();
ser.Serialize(sw, c3);
XmlDocument doc = new XmlDocument();
doc.LoadXml(sw.ToString());
XslTransform xslt = new XslTransform();
xslt.Load("C:\\C3.xsl");
XmlTextWriter wrt = new XmlTextWriter(Console.Out);
wrt.Formatting = Formatting.Indented;
xslt.Transform(doc, null, wrt, null);
Console.WriteLine();
}
public static void Main(string[] args)
{
C3 c3 = new C3();
c3.f1 = "a";
c3.f2 = "bb";
c3.f3 = "ccc";
standard(c3);
transformed(c3);
}
}
C3.xsl indeholder:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="
http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="C3">
<C3>
<xsl:apply-templates/>
</C3>
</xsl:template>
<xsl:template match="f1">
<x key="f1"><xsl:value-of select="."/></x>
</xsl:template>
<xsl:template match="f2">
<x key="f2"><xsl:value-of select="."/></x>
</xsl:template>
<xsl:template match="f3">
<x key="f3"><xsl:value-of select="."/></x>
</xsl:template>
</xsl:stylesheet>
Output bliver:
Standard:
<?xml version="1.0" encoding="IBM437"?>
<C3 xmlns:xsd="
http://www.w3.org/2001/XMLSchema" xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"> <f1>a</f1>
<f2>bb</f2>
<f3>ccc</f3>
</C3>
Transformed:
<C3>
<x key="f1">a</x>
<x key="f2">bb</x>
<x key="f3">ccc</x>
</C3>