Andrey Bushman
Andrey Bushman

Reputation: 12506

The XslCompiledTransform output encoding

My code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Xsl;

namespace xslt_samples {
    class Program {
        static void Main(string[] args) {
            XslCompiledTransform myXslTransform = new XslCompiledTransform();

            // Here the myXslTransform.OutputSettings is null still...          
            myXslTransform.Load(@".\in3.xsl");

            // The myXslTransform.OutputSettings is not null now, but
            // I get an exception: the XmlWriterSettings.Encoding read only.
            myXslTransform.OutputSettings.Encoding = Encoding.UTF8;

            myXslTransform.Transform(@".\in.xml", @".\out.xml");
        }
    }
}

The problem is pointed it the comments.

How can I set the output encoding in this case?

Thank you.

Upvotes: 1

Views: 3548

Answers (2)

Martin Honnen
Martin Honnen

Reputation: 167581

Use

        XmlWriterSettings xws = myXslTransform.OutputSettings.Clone();
        xws.Encoding = Encoding.UTF8;

        using (XmlWriter xw = XmlWriter.Create("out.xml", xws))
        {
          myXslTransform.Transform(@".\in.xml", xw);
        }

Upvotes: 2

Tomalak
Tomalak

Reputation: 338248

This is straight from the docs.

XslCompiledTransform.OutputSettings Property

Gets an XmlWriterSettings object that contains the output information derived from the xsl:output element of the style sheet.

Syntax

public XmlWriterSettings OutputSettings { get; }

It's a read-only property.

The docs go on with

Remarks

This property is populated after a successful call to the Load method. It contains information derived from the xsl:output element of a compiled style sheet.

This XmlWriterSettings object can be passed to the XmlWriter.Create method to create the XmlWriter object to which you want to output.

Conclusions:

  • The XmlWriter accepts a custom XmlWriterSettings object.
  • The XslCompiledTransform does not.

Upvotes: 1

Related Questions