使用StringWriter,StringBuilder和XmlTextWriter加载XML并将其写入字符串

时间:2018-02-16 00:17:37

标签: c# xml xml-serialization xmlwriter

我在给定位置有一个XML文件,我希望在字符串变量中包含XML的内容。但是,当我打印出来时,编码会发生变化。这就是我的做法。

    XmlDocument xmlFile = new XmlDocument();
    xmlFile.Load(xmlFileLocation);

    using (StringWriter stringWriter = new StringWriter(new StringBuilder()))
    {
         using (XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter) { Formatting = Formatting.Indented })
         {
             xmlFile.Save(xmlTextWriter);
         }

         return stringWriter.ToString();
    }

当我尝试使用给定的编码初始化XmlTextWriter(new XmlTextWriter(stringWriter,Encoding.UTF8))时,我遇到了StringWriter的问题,但我不知道如何对其进行排序。有什么想法吗?

问题是:无法从StringWriter转换为Stream

1 个答案:

答案 0 :(得分:0)

使用StringWriter进行编码始终为UTF-16,无法更改。如果要使用具有不同编码的StringWriter,则可以继承StringWriter。有关如何操作,请参阅this答案。

使用您的代码,然后将更改为

using (EncodingStringWriter eStringWriter = new EncodingStringWriter (new StringBuilder(), Encoding.UTF8))
{
     using (XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter) { Formatting = Formatting.Indented })
     {
         xmlFile.Save(xmlTextWriter);
     }

     return eStringWriter.ToString();
}