此操作将创建结构不正确的文档

我是XML新手并尝试了以下但我得到了一个例外。 有人能帮我吗?

例外是This operation would create an incorrectly structured document

我的代码:

 string strPath = Server.MapPath("sample.xml"); XDocument doc; if (!System.IO.File.Exists(strPath)) { doc = new XDocument( new XElement("Employees", new XElement("Employee", new XAttribute("id", 1), new XElement("EmpName", "XYZ"))), new XElement("Departments", new XElement("Department", new XAttribute("id", 1), new XElement("DeptName", "CS")))); doc.Save(strPath); } 

Xml文档必须只有一个根元素。 但是您尝试在根级别添加DepartmentsEmployees节点。 添加一些根节点来解决此问题:

 doc = new XDocument( new XElement("RootName", new XElement("Employees", new XElement("Employee", new XAttribute("id", 1), new XElement("EmpName", "XYZ"))), new XElement("Departments", new XElement("Department", new XAttribute("id", 1), new XElement("DeptName", "CS")))) ); 

您需要添加根元素。

 doc = new XDocument(new XElement("Document")); doc.Root.Add( new XElement("Employees", new XElement("Employee", new XAttribute("id", 1), new XElement("EmpName", "XYZ")), new XElement("Departments", new XElement("Department", new XAttribute("id", 1), new XElement("DeptName", "CS"))))); 

在我的情况下,我试图向xDocument添加多个XElement,这会抛出此exception。 请参阅下面的正确代码以解决我的问题

 string distributorInfo = string.Empty; XDocument distributors = new XDocument(); XElement rootElement = new XElement("Distributors"); XElement distributor = null; XAttribute id = null; distributor = new XElement("Distributor"); id = new XAttribute("Id", "12345678"); distributor.Add(id); rootElement.Add(distributor); distributor = new XElement("Distributor"); id = new XAttribute("Id", "22222222"); distributor.Add(id); rootElement.Add(distributor); distributors.Add(rootElement); distributorInfo = distributors.ToString(); 

请参阅下面我在distributorInfo中获得的内容