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 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@padman - you can subclass StringWriter and override Encoding - that should so it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.