好吧,這是我會做什麼來創建反思基礎的CSV。我想序列化對象到XML,然後將生成的XML使用XSLT轉換CSV:
namespace ConsoleApplication1
{
[XmlRoot(ElementName = "Players")]
public class Players : System.Collections.Generic.List<Player> {
public Players() { }
}
public class Player{
public string Name { get; set; }
public string Team { get; set; }
public string Position { get; set; }
public Player(string name, string position, string team) {
this.Name = name;
this.Position = position;
this.Team = team;
}
public Player() { }
}
[System.Runtime.InteropServices.GuidAttribute("D36900FE-8902-4ED8-B961-DE5B3F3273AC")]
class Program
{
static void Main(string[] args)
{
Players players= new Players();
players.Add(new Player("C.Ronaldo", "Man Utd", "Midfielder"));
XmlSerializer ser = new XmlSerializer(typeof(Players));
var writer = new System.IO.StreamWriter(@"C:\myxml.xml", false);
ser.Serialize(writer, players);
writer.Flush();
writer.Close();
var myXslTrans = new XslCompiledTransform();
myXslTrans.Load(@"C:\CSV.xslt", null, null);
myXslTrans.Transform(@"file://C:/myxml.xml", @"C:\converted.csv");
}
}
}
這是我的示例XSLT:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:telerik="remove" xmlns:asp="remove">
<xsl:template match="/">
<xsl:for-each select="Players/Player">
<xsl:value-of select="Name" />,<xsl:value-of select="Team" />,<xsl:value-of select="Position" />
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
免責聲明:
I know the XSLT needs break lines or may need additional formats. I only intent to describe a possible path to CSV/Reflection and not a fully working solution.