XmlWriter encoding UTF-8 using StringWriter in C#

后端 未结 2 1875
被撕碎了的回忆
被撕碎了的回忆 2021-01-12 16:37

I\'m using C# to output an xml file and Im trying to set the xml encoding value to UTF-8 but its currently outputting:


<         


        
相关标签:
2条回答
  • 2021-01-12 17:10

    Your code does not compile -- StringWriterWithEncoding does not have a parameterless constructor. Or, if it does have a parameterless constructor, maybe it actually looks like this?

    public sealed class StringWriterWithEncoding : StringWriter
    {
        private readonly Encoding encoding;
    
        public StringWriterWithEncoding() { }
    
        public StringWriterWithEncoding(Encoding encoding)
        {
            this.encoding = encoding;
        }
    
        public override Encoding Encoding
        {
            get { return encoding; }
        }
    }
    

    If so, that would explain your problem - the field encoding has been left at its default (null) value, meaning Encoding returns null, and so no encoding will appear in the XML file.

    To fix it, eliminate the parameterless constructor, and do:

    var sw = new StringWriterWithEncoding(Encoding.UTF8);
    

    Or change the parameterless constructor to explicitly set Encoding.UTF8:

    public sealed class StringWriterWithEncoding : StringWriter
    {
        private readonly Encoding encoding;
    
        public StringWriterWithEncoding() : this(Encoding.UTF8) { }
    
        public StringWriterWithEncoding(Encoding encoding)
        {
            this.encoding = encoding;
        }
    
        public override Encoding Encoding
        {
            get { return encoding; }
        }
    }
    
    0 讨论(0)
  • 2021-01-12 17:19

    Just use the output file name for the XmlWriter instead of the StringWriterWithEncoding:

    var settings = new XmlWriterSettings
    {
        Encoding = Encoding.UTF8,
        Indent = true
    };
    
    using (var writer = XmlWriter.Create(filePathName, settings))
    {
        ...
    
    0 讨论(0)
提交回复
热议问题