Posts Tagged ‘xslt’

Using WCF to return HTML

I just answered a WCF question on StackOverflow, and decided it was worth cross-posting here as well.

The question was: What is the best / most flexible way to have WCF output XHTML?

Here’s how we do it at Infovark. While I’m not sure that our approach is the best way, it does the job.

Our approach is to use the DataContractSerilizer to generate XML, then apply a Complied XSLT transform and return the result stream, which should now contain XHTML. Here’s a simplified version of our code:

  1.     public Stream GetItemAsHtml(string id) {
  2.         Item obj = GetItem(objectId);
  3.         Stream xml = GetXmlStream(obj);    
  4.         return TransformXmlStream(xml, defaultTransform);
  5.     }        
  6.  
  7.     public static Stream GetXmlStream(IXmlSerializable item) {
  8.         MemoryStream stream = new MemoryStream();
  9.         using (XmlWriter writer = XmlWriter.Create(stream, new XmlWriterSettings { Encoding = Encoding.UTF8 })) {
  10.             if (writer != null) {
  11.                 DataContractSerializer dcs = new DataContractSerializer(item.GetType());
  12.                 dcs.WriteObject(writer, item);
  13.  
  14.                 writer.Flush();
  15.                 writer.Close();
  16.             }
  17.         }
  18.         stream.Seek(0, SeekOrigin.Begin);
  19.         return stream;
  20.     }
  21.  
  22.     public static Stream TransformXmlStream(Stream xml, string xsltFile) {
  23.         XmlReader reader = XmlReader.Create(xml);
  24.  
  25.         XslCompiledTransform trans = new XslCompiledTransform();
  26.         trans.Load(xsltFile);
  27.  
  28.         MemoryStream stream = new MemoryStream();
  29.         using (XmlWriter writer = XmlWriter.Create(stream, trans.OutputSettings)) {
  30.             if (writer != null) {
  31.                 trans.Transform(reader, writer);
  32.  
  33.                 writer.Flush();
  34.                 writer.Close();
  35.             }
  36.         }
  37.         stream.Seek(0, SeekOrigin.Begin);
  38.         return stream;
  39.     }

It works for us, but if you’ve got other, better ideas, please let me know!