views:

505

answers:

3

So, I am working with .NET. I have an XSL file, XslTransform object in C# that reads in the XSL file and transforms a piece of XML data (manufactured in-house) into HTML.

I notice that my final output has < and > automatically encoded into &lt; and &gt;. Is there any ways I can prevent that from happening? Sometimes I need to bold or italicize my text but it's been unintentionally sanitized.

A: 

(XslTransform is deprecated, according to MSDN. They recommend you switch to XslCompiledTransform.)

Can you post an example of the input/output?

Assaf Lavie
+1  A: 

I have used this in the past to transform XMl documents into HTML strings which is what you need.

public static string TransformXMLDocFromFileHTMLString(string orgXML, string transformFilePath)
{
    System.Xml.XmlDocument orgDoc = new System.Xml.XmlDocument();
    orgDoc.LoadXml(orgXML);

    XmlNode transNode = orgDoc.SelectSingleNode("/");
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    XmlWriterSettings settings = new XmlWriterSettings();

    settings.ConformanceLevel = ConformanceLevel.Auto;
    XmlWriter writer = XmlWriter.Create(sb, settings);

    System.Xml.Xsl.XslCompiledTransform trans = new System.Xml.Xsl.XslCompiledTransform();
    trans.Load(transformFilePath);

    trans.Transform(transNode, writer);

    return sb.ToString();
}
David Basarab
+1  A: 

Your xsl file should have:

  • an output of html
  • omit namespaces for all used in the xslt

i.e.

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt"
    exclude-result-prefixes="xsl msxsl">

    <xsl:output method="html" indent="no" omit-xml-declaration="yes"/>

    <!-- lots -->
</xsl:stylesheet>

And you should ideally use the overloads that accept either a TextWriter or a Stream (not XmlWriter) - i.e. something like:

StringBuilder sb = new StringBuilder();
using (XmlReader reader = XmlReader.Create(source)
using (TextWriter writer = new StringWriter(sb))
{
    XslCompiledTransform xslt = new XslCompiledTransform();
    xslt.Load("Foo.xslt"); // in reality, you'd want to cache this
    xslt.Transform(reader, options.XsltOptions, writer);
}
string html = sb.ToString();

In the xslt, if you really want standalone < / > (i.e. you want it to be malformed for some reason), then you need to disable output escaping:

<xsl:text disable-output-escaping="yes">
    Your malformed text here
</xsl:text>

However, in general it is correct to escape the characters.

Marc Gravell