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

本文关键字:不正确 文档 结构 创建 操作 | 更新日期: 2023-09-27 17:49:45

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

在我的情况下,我试图添加多个XElement到抛出此异常的xDocument。请参阅下面我的正确代码,解决了我的问题

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>