且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 C# 中,将字符串格式化为 XML 的***方法是什么?

更新时间:2023-02-09 15:29:12

string unformattedXml = "<?xml version="1.0"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>";
string formattedXml = XElement.Parse(unformattedXml).ToString();
Console.WriteLine(formattedXml);

输出:

<book>
  <author>Lewis, C.S.</author>
  <title>The Four Loves</title>
</book>

Xml 声明不是由 ToString() 输出,而是由 Save() 输出...

The Xml Declaration isn't output by ToString(), but it is by Save() ...

  XElement.Parse(unformattedXml).Save(@"C:doc.xml");
  Console.WriteLine(File.ReadAllText(@"C:doc.xml"));

输出:

<?xml version="1.0" encoding="utf-8"?>
<book>
  <author>Lewis, C.S.</author>
  <title>The Four Loves</title>
</book>