第三步:代碼產生引擎
自動代碼產生方案很多,這裡為了配置模板方便,就使用了最常見的XML+XSLT模板方式。
核心代碼如下:
public static bool TransferXml(XmlDocument xmlDoc, string XslPath, string TargetFileName){ XslCompiledTransform xslTran = new XslCompiledTransform(); XmlTextWriter xw = null; try { xw = new XmlTextWriter(TargetFileName, Encoding.UTF8); xslTran.Load(XslPath); xslTran.Transform(xmlDoc, xw); return true; } catch { return false; } finally { if (xw != null) { xw.Flush(); xw.Close(); } }}public static string TransferXmlToString(XmlDocument XmlDoc, string XsltPath){ //擷取Model類模板 string ResultStr = ""; MemoryStream ms = null; StreamReader sr = null; try { XslCompiledTransform XTran = new XslCompiledTransform(); XTran.Load(XsltPath); ms = new System.IO.MemoryStream(); XPathNavigator nav = XmlDoc.CreateNavigator(); XTran.Transform(nav, null, ms); ms.Position = 0; sr = new StreamReader(ms); ResultStr = sr.ReadToEnd(); ResultStr = ResultStr.Replace("<?xml version=/"1.0/" encoding=/"utf-8/"?>", ""); return ResultStr; } catch { return ""; } finally { if (sr != null) { sr.Close(); sr.Dispose(); } if (ms != null) { ms.Dispose(); } }}
好了,現在為止,代碼產生工具就基本完成了。