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

C# 此操作将创建结构不正确的文档,c#,asp.net,.net,linq,linq-to-xml,C#,Asp.net,.net,Linq,Linq To Xml,我不熟悉XML,尝试了以下方法,但遇到了一个异常。有人能帮我吗 例外情况是此操作将创建结构不正确的文档 我的代码: string strPath = Server.MapPath("sample.xml"); XDocument doc; if (!System.IO.File.Exists(strPath)) { doc = new XDocument( new XElement("Employees", new XElement("Employ

我不熟悉
XML
,尝试了以下方法,但遇到了一个异常。有人能帮我吗

例外情况是
此操作将创建结构不正确的文档

我的代码:

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文档必须只有一个根元素。但是您正在尝试在根级别添加
部门
员工
节点。添加一些根节点以修复此问题:

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,这些XElement会引发此异常。请参阅下面我解决问题的正确代码

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中得到的信息

<Distributors>
 <Distributor Id="12345678" />
 <Distributor Id="22222222" />
</Distributors>

他们可能会考虑将此错误消息更加明确。类似于“XML文档可能只有一个根元素”。即使知道这个事实,单凭这个错误信息也很难理解这个问题。