0

I have written below code to convert XML file to UTF-8 format file, it is working as excepted but issue is header is concatenating with body text instead of writing in separate line. I need utf8 in seperate line but file.writealltext will not accept more than 3 arguments/parameters. Any help appreciated.

        string path = @"samplefile.xml";
        string path_new = @"samplefile_new.xml";

        Encoding utf8 = new UTF8Encoding(false);
        Encoding ansi = Encoding.GetEncoding(1252);

        string xml = File.ReadAllText(path, ansi);

        XDocument xmlDoc = XDocument.Parse(xml);

        File.WriteAllText(
            path_new,
            @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""true"">" + xmlDoc.ToString(),

           utf8
        );
Koti Raavi
  • 300
  • 2
  • 13
  • 3
    Possible duplicate of [How to add a newline (line break) in XML file?](https://stackoverflow.com/questions/35504890/how-to-add-a-newline-line-break-in-xml-file) – Tiago Silva Oct 29 '19 at 13:20
  • 2
    `...true"">" + Environment.NewLine + xmlDoc.ToString(),` – Igor Oct 29 '19 at 13:24
  • It's working :) thank you so much, i have tried previously same thing after tostring()..now i got to know that we need to add right after xml. – Koti Raavi Oct 29 '19 at 13:29
  • Silva, it's not duplicate, the one you shared pure xml one, one i'm looking is converting xml to UTF-8 with c# code. context is different. – Koti Raavi Oct 29 '19 at 13:31

1 Answers1

1

No need to use any API other than LINQ to XML. It has all means to deal with XML file encoding, prolog, BOM, indentation, etc.

void Main()
{
    string outputXMLfile = @"e:\temp\XMLfile_UTF-8.xml";

    XDocument xml = XDocument.Parse(@"<?xml version='1.0' encoding='utf-16'?>
                    <root>
                        <row>some text</row>
                    </root>");

    XDocument doc = new XDocument(
        new XDeclaration("1.0", "utf-8", null),
        new XElement(xml.Root)
    );


    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    settings.IndentChars = "\t";
    // to remove BOM
    settings.Encoding = new UTF8Encoding(false);

    using (XmlWriter writer = XmlWriter.Create(outputXMLfile, settings))
    {
        doc.Save(writer);
    }
}
Yitzhak Khabinsky
  • 18,471
  • 2
  • 15
  • 21