XDocument 保存,无需换行符
本文关键字:换行符 保存 XDocument | 更新日期: 2023-09-27 18:34:22
我正在使用XDocument写入XML文件。写入完成后,XML 不是人类可读的,因为换行符几乎完全被省略。
XDocument xmlDoc = new XDocument();
XElement xmlRoot = new XElement("root", "root");
XElement xmlEntry = new XElement("file",
new XAttribute("name", "Example"),
new XAttribute("hashcode", "Hashcode Example")
);
xmlRoot.Add(xmlEntry);
xmlDoc.Add(xmlRoot);
xmlDoc.Save("C:''contents.xml");
我已经尝试了xmlDoc.Save()行的各种选项,包括:
xmlDoc.Save("...", SaveOptions.DisableFormatting);
xmlDoc.Save("...", SaveOptions.None);
请注意,我提交的代码是我的程序实际包含的代码的简化形式;功能上是相同的。
上面
只是调用xmlDoc.Save("C:''contents.xml")
的代码正在以"漂亮"格式保存xml。 它只是没有按照您期望的方式格式化它。 我认为问题是因为您要向同一节点添加文本值和子节点,因此解析器可能不知道如何或具体不会分解这些值。
如果修改代码以生成没有文本值的"root"元素,它将以您可能期望的方式显示 XML。 我用这段代码进行了测试:
XDocument xmlDoc = new XDocument();
XElement xmlRoot = new XElement("root");
XElement xmlEntry = new XElement("file",
new XAttribute("name", "Example"),
new XAttribute("hashcode", "Hashcode Example with some long string")
);
xmlRoot.Add(xmlEntry);
xmlDoc.Add(xmlRoot);
xmlDoc.Save("temp.xml");
Console.WriteLine(System.IO.File.ReadAllText("temp.xml"));
生成上述内容的更简洁的方法可以与此代码一起使用,我也发现它更具可读性:
XDocument xmlDoc = new XDocument();
xmlDoc.Add(
new XElement("root",
new XElement("file",
new XAttribute("name", "example"),
new XAttribute("hashcode", "hashcode example")
)
)
);
xmlDoc.Save("temp.xml");
Console.WriteLine(System.IO.File.ReadAllText("temp.xml"));