C# 使用C语言将XML转换为UTF-8#

C# 使用C语言将XML转换为UTF-8#,c#,xml,c#-4.0,C#,Xml,C# 4.0,我已经写了下面的代码来将XML文件转换成UTF-8格式的文件,这是一个例外,但问题是标题和正文文本连接在一起,而不是在单独的行中写入。我需要在单独的行中使用utf8,但file.writealText将不接受超过3个参数。谢谢你的帮助 string path = @"samplefile.xml"; string path_new = @"samplefile_new.xml"; Encoding utf8 = new UTF8Encoding(

我已经写了下面的代码来将XML文件转换成UTF-8格式的文件,这是一个例外,但问题是标题和正文文本连接在一起,而不是在单独的行中写入。我需要在单独的行中使用utf8,但file.writealText将不接受超过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
        );
stringpath=@“samplefile.xml”;
字符串路径_new=@“samplefile_new.xml”;
编码utf8=新的utf8编码(假);
Encoding ansi=Encoding.GetEncoding(1252);
字符串xml=File.ReadAllText(路径,ansi);
XDocument xmlDoc=XDocument.Parse(xml);
File.writealText(
新路,
@“”+xmlDoc.ToString(),
utf8
);

无需使用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);
    }
}
void Main()
{
字符串outputXMLfile=@“e:\temp\XMLfile_UTF-8.xml”;
XDocument xml=XDocument.Parse(@)
一些文本
");
XDocument doc=新XDocument(
新XDeclaration(“1.0”,“utf-8”,空),
新XElement(xml.Root)
);
XmlWriterSettings=新的XmlWriterSettings();
settings.Indent=true;
settings.IndentChars=“\t”;
//删除BOM表的步骤
settings.Encoding=新的UTF8Encoding(false);
使用(XmlWriter=XmlWriter.Create(输出xmlfile,设置))
{
保存文档(编写器);
}
}

可能重复的
…true”“>”+Environment.NewLine+xmlDoc.ToString(),
它正在工作:)非常感谢,我在ToString()之后尝试过同样的方法…现在我知道我们需要在xml之后添加。Silva,它不是重复的,您共享的是纯xml,我正在寻找的是用c代码将xml转换为UTF-8。上下文不同。