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
        );
4
  • 3
    Possible duplicate of How to add a newline (line break) in XML file? Commented Oct 29, 2019 at 13:20
  • 2
    ...true"">" + Environment.NewLine + xmlDoc.ToString(), Commented Oct 29, 2019 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. Commented Oct 29, 2019 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. Commented Oct 29, 2019 at 13:31

1 Answer 1

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.