Question

Using the following code:

XDocument transformedDoc = new XDocument();
        using (XmlWriter writer = transformedDoc.CreateWriter())
        {
            XslCompiledTransform transform = new XslCompiledTransform();
            //transform.Load(XmlReader.Create(new StringReader(HttpContext.Current.Server.MapPath("~/XML/CareLog.xsl"))));
            transform.Load(HttpContext.Current.Server.MapPath("~/XML/CareLog.xsl"));
            transform.Transform(doc.CreateReader(), writer);
        }

I have some strings from a database that contain <br /> for a line return(as used elsewhere). Whatever I replace this with, Environment.NewLine, \n, etc it will never put line breaks in the transformed document.

EDIT

Replaced line breaks with \r\n and changed as per suggestion below:

var xslt = new XslCompiledTransform();
xslt.Load(HttpContext.Current.Server.MapPath("~/XML/CareLogresidenceSummary.xsl"));
var settings = xslt.OutputSettings.Clone();
settings.NewLineChars = "\n";
using (var reader = doc.CreateReader())
{
    using (var writer = XmlWriter.Create(HttpContext.Current.Server.MapPath("~/BrowserTemp/CareLogResidenceSummary.xml"), settings))
    {
        xslt.Transform(reader, writer);
    }
}

Still creates transformed document ok, but still does not put anything onto a new line. For reference I am renaming the transformed document with a .doc extension to open in word, the XML has the line breaks but not when opened in Word.

Was it helpful?

Solution

You should use "\r\n" for representing new lines.

There are two ways you can handle the newlines:

  1. Set-up the writer to use specific characters when writing new lines using the NewLineChars option.

  2. Instruct the writer not to modify the new lines using the NewLineHandling option

So you could modify your code as follows to preserve the new lines:

var xslt = new XslCompiledTransform();
xslt.Load(HttpContext.Current.Server.MapPath("~/XML/CareLog.xsl"));
var settings = xslt.OutputSettings.Clone();
settings.NewLineChars = "\n";
settings.NewLineHandling = NewLineHandling.Replace;
using (var reader = XmlReader.Create("example.xml"))
{
 using (var writer = XmlWriter.Create("yourDoc.txt", settings))
 {
   xslt.Transform(reader, writer);
 }
}

Note that I haven't run this. The only thing you'll need to do is get your file into the call to "XmlWriter.Create()".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top