views:

19

answers:

1

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.

+1  A: 

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
Marc Gravell
Thanks for the response.Yes you are correct if i directly write to a file it works. but i need that stringbuilder object for processing the xml contents further later and then i will write to the file. Because i am using this stringbuilder object it is writing it as UTF-16.
Chitti
@padman - you can subclass StringWriter and override Encoding - that should so it.
Marc Gravell