How do I XmlDocument.Save() to encoding=“us-ascii” with numeric character entities instead of question marks?

后端 未结 1 1347
别那么骄傲
别那么骄傲 2021-01-15 17:12

My goal is to get a binary buffer (MemoryStream.ToArray() would yield byte[] in this case) of XML without losing the Unicode characters. I would ex

相关标签:
1条回答
  • 2021-01-15 17:52

    You can use XmlWriter instead:

      var doc = new XmlDocument();
        doc.LoadXml("<x>“∞π”</x>");
        using (var buf = new MemoryStream())
        {
            using (var writer =  XmlWriter.Create(buf, 
                  new XmlWriterSettings{Encoding= Encoding.ASCII}))
            {
                doc.Save(writer);
            }
            Console.Write(Encoding.ASCII.GetString(buf.ToArray()));
        }
    

    Outputs:

    <?xml version="1.0" encoding="us-ascii"?><x>&#x201C;&#x221E;&#x3C0;&#x201D;</x> 
    
    0 讨论(0)
提交回复
热议问题