




推荐使用XDocument创建空XML文档并添加根节点,如new XDocument(new XElement("Books"));若用XmlDocument则需CreateElement再AppendChild;XDocument还支持自动XML声明和命名空间。
在C#中,创建一个空的XML文档并添加根节点,推荐使用 XDocument(来自 System.Xml.Linq),它简洁、现代且支持函数式构造。
这是最常用、最直观的方式:
XDocument.Create 或直接 new XDocument() 得到空文档new XElement("根元素名") 创建根节点Root 属性,或在构造时传入示例代码:
using System.Xml.Linq;
XDocument doc = new XDocument();
doc.Root = new XElement("Books"); // 添加根节点
// 或更简洁地一步完成:
// XDocument doc = new XDocument(new 
XElement("Books"));
Console.WriteLine(doc.ToString()); // 输出:
如果项目仍使用传统的 XmlDocument(位于 System.Xml),流程稍多几步:
XmlDocument 实例CreateElement 创建根元素AppendChild 将其添加为文档的首个子节点(即根)示例代码:
using System.Xml;
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("Catalog");
doc.AppendChild(root);
Console.WriteLine(doc.OuterXml); // 输出:
若需带 XML 声明(如 )或默认命名空间,XDocument 更方便:
XDocument 时默认生成 XML 声明new XElement("{http://example.com}Books")
new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XElement("Root"))
完成后可轻松输出:
doc.Save("output.xml") —— 保存到文件doc.ToString() 或 doc.ToString(SaveOptions.None) —— 获取格式化字符串doc.ToString(SaveOptions.DisableFormatting) —— 获取紧凑格式(无缩进)