0

I have an XML file on a given location and I want to have the content of the XML in a string variable. However, when I print it out, the encoding changes. This is how I am doing it.

    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();
    }

When I try to initialize the XmlTextWriter (new XmlTextWriter(stringWriter, Encoding.UTF8)) with a given encoding, then I have issues with the StringWriter but I don't know how to sort it out. Any idea?

The issue is: Cannot convert from StringWriter into Stream

user3587624
  • 1,427
  • 5
  • 29
  • 60
  • What's wrong with ``xmlFile.OuterXml`` (see https://stackoverflow.com/questions/2407302/convert-xmldocument-to-string)? – dumetrulo Feb 16 '18 at 09:01
  • Just use [`File.ReadAllText`](https://msdn.microsoft.com/en-us/library/system.io.file.readalltext(v=vs.110).aspx)? It's not entirely clear what you mean by 'the encoding changes', but I'm going to guess it's a duplicate of [this question](https://stackoverflow.com/questions/1564718/using-stringwriter-for-xml-serialization). – Charles Mager Feb 16 '18 at 09:08

1 Answers1

0

Encoding using StringWriter always will be UTF-16 and cannot be changed. When you want to use a StringWriter with different encoding it is possible to subclass StringWriter. Please refer to this answer on how to do so.

Using your code this would then change to

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

     return eStringWriter.ToString();
}
Shique
  • 724
  • 3
  • 18