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

时间:2012-12-29 12:48:10

标签: c# asp.net .net linq linq-to-xml

我是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);
}

3 个答案:

答案 0 :(得分:27)

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"))))
                );

答案 1 :(得分:12)

您需要添加根元素。

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")))));

答案 2 :(得分:2)

在我的情况下,我试图向xDocument添加多个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>