How do I preserve special characters when writing XML with XDocument.Save()?

前端 未结 4 1828
再見小時候
再見小時候 2021-01-22 22:01

My source XML has the copyright character in it as ©. When writing the XML with this code:

var stringWriter = new StringWriter();
segment         


        
4条回答
  •  时光说笑
    2021-01-22 22:40

    I strongly suspect you won't be able to do this. Fundamentally, the copyright sign is © - they're different representations of the same thing, and I expect that the in-memory representation normalizes this.

    What are you doing with the XML afterwards? Any sane application processing the resulting XML should be fine with it.

    You may be able to persuade it to use the entity reference if you explicitly encode it with ASCII... but I'm not sure.

    EDIT: You can definitely make it use a different encoding. You just need a StringWriter which reports that its "native" encoding is UTF-8. Here's a simple class you can use for that:

    public class Utf8StringWriter : StringWriter
    {
        public override Encoding Encoding
        {
             get { return Encoding.UTF8; }
        }
    }
    

    You could try changing it to use Encoding.ASCII as well and see what that does to the copyright sign...

提交回复
热议问题