c# - 使用 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
);
解决方案
无需使用除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);
}
}
推荐阅读
- latex - 在背面将编译器更改为 XeLeTax 但仍然失败
- reporting-services - SSRS 多列报表分页不正确
- java - 在java中从JSON中删除评论的最快方法?
- multithreading - 运行单独线程的结果不清楚
- scala - 如何在 Slick 中设置获取大小?
- python - 如何使用xpath和scrapy使用href从该站点提取URL?
- javascript - 我可以在同一个函数中使用多个拼接方法吗?JavaScript
- c - *NIX read()/write():它们是可重入的吗?
- c# - 在 Autofac/c# 的方法中作为参数传递时解析类型(请查看示例代码)
- html - 使用“script-src”允许网站不会影响错误