Question

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.

Was it helpful?

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top