using System; using System.Xml.Xsl; using System.Xml; using System.IO.Ports; using System.IO; using System.Text; // copy alphasign.xsl // from http://pobox.com/~dfranklin/bbxml/bbxml/xml/alphasign.xsl // compile: csc AlphasignXMLApp.cs // run: AlphaSignXMLApp.exe -port COM1 -xsl alphasign.xsl -xml hello.xml public class AlphaSignXMLApp { private String serialPortName; private String xslFileName; private String xmlFileName; /** * Command line args: * */ public static void Main(String[] args) { AlphaSignXMLApp app = new AlphaSignXMLApp(); for (int i = 0; i < args.Length; i++) { if ("-port" == args[i]) { app.setSerialPortName(args[++i]); } else if ("-xsl" == args[i]) { app.setXSLFileName(args[++i]); } else if ("-xml" == args[i]) { app.setXMLFileName(args[++i]); } } app.run(); } public void setSerialPortName(String serialPortName) { this.serialPortName = serialPortName; } public String getSerialPortName() { return serialPortName; } public void setXSLFileName(String xslFileName) { this.xslFileName = xslFileName; } public String getXSLFileName() { return xslFileName; } public void setXMLFileName(String xmlFileName) { this.xmlFileName = xmlFileName; } public String getXMLFileName() { return xmlFileName; } public void run() { try { // create a buffer for the XSLT output MemoryStream memStream = new MemoryStream(1024); transform(memStream); memStream.Seek(0, SeekOrigin.Begin); // write the buffer to the serial port writeToSerialPort(memStream); } catch (Exception e) { Console.WriteLine(e); } } /** * Transform the XML file using the XSL file, writing result to the * specified OutputStream. */ public void transform(Stream stream) { XslCompiledTransform xslt = new XslCompiledTransform(); XsltSettings xsltSettings = new XsltSettings(); // it complains if we don't do this (I guess it's a security feature) xsltSettings.EnableDocumentFunction = true; xslt.Load(xslFileName, xsltSettings, null); // The output encoding specified in alphasign.xsl is UTF-8. // By default Transform includes a Byte Order Mark, which we do not want. // We fix that by passing false to the UTF8Encoding constructor. // Alternatively, alphasign.xsl could specify , // which is actually more appropriate for the Alpha sign, but that causes // the transform to fail completely when the input text contains non-ASCII // characters. I prefer to let it output a few garbage characters rather // than fail completely. XmlTextWriter writer = new XmlTextWriter(stream, new UTF8Encoding(false)); xslt.Transform(xmlFileName, writer); } /** * Read from InputStream and write to the serial port. */ public void writeToSerialPort(Stream inStream) { // get, open, and configure the serial port SerialPort serialPort = new SerialPort(serialPortName, 9600, Parity.Even, 7, StopBits.Two); serialPort.Handshake = Handshake.None; serialPort.Open(); // write the data int b; while (-1 != (b = inStream.ReadByte())) { byte[] buf = new byte[1]; buf[0] = (byte)b; serialPort.Write(buf, 0, 1); } serialPort.Close(); } }