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

前端 未结 4 1874
再見小時候
再見小時候 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:41

    It appears that UTF8 won't solve the problem. The following has the same symptoms as your code:

    MemoryStream ms = new MemoryStream();
    XmlTextWriter writer = new XmlTextWriter(ms, new UTF8Encoding());
    segmentDoc.Save(writer);
    ms.Seek(0L, SeekOrigin.Begin);
    var reader = new StreamReader(ms);
    var result = reader.ReadToEnd();
    Console.WriteLine(result);
    

    I tried the same approach with ASCII, but wound up with ? instead of ©.

    I think using a string replace after converting the XML to a string is your best bet to get the effect you want. Of course, that could be cumbersome if you are interested in more than just the @copy; symbol.

    result = result.Replace("©", "\u0026#x00A9;");
    

提交回复
热议问题