首页 > 解决方案 > 使用 C# 将 XML 转换为 UTF-8

问题描述

我在下面编写了将 XML 文件转换为 UTF-8 格式文件的代码,它可以正常工作,但问题是标题与正文连接,而不是在单独的行中写入。我需要 utf8 在单独的行中,但 file.writealltext 不会接受超过 3 个参数/参数。任何帮助表示赞赏。

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

标签: c#xmlc#-4.0

解决方案


无需使用除LINQ to XML之外的任何 API 。它拥有处理XML文件编码、prolog、BOM、缩进等的一切手段。

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

推荐阅读