Search code examples
c#xmlxmlreaderxmlwriterxslt

How to create a XML with a Specific Encoding using XSLT and XMLWRITER


I am trying to apply a XSL style sheet on a source xml and write the output to a target xml file. The xsl removes the xml comments present inside the source xml.

The target xml file has UTF-16 encoding in the header.

But still i want the output xml to be utf-8 encoding. The code i used is

            XmlWriterSettings xwrSettings = new XmlWriterSettings();
            **xwrSettings.Encoding = Encoding.UTF8;**

            XslCompiledTransform xslt = new XslCompiledTransform();
            xslt.Load("sample.xsl");
            StringBuilder sb = new StringBuilder();
            XmlReader xReader = XmlReader.Create("Source.xml");
            XmlWriter xWriter = XmlWriter.Create(sb, xwrSettings);                
            xslt.Transform(xReader, xWriter);
            File.WriteAllText("Target.xml",sb.ToString());

I tried to set the xml writer setting to be of UTF-8 but it is not working.


Solution

  • Since you are writing to file, why not just use:

    using (XmlReader xReader = XmlReader.Create("Source.xml"))
    using (XmlWriter xWriter = XmlWriter.Create("Target.xml", xwrSettings)) {
        xslt.Transform(xReader, xWriter);
    }
    // your file is now written