此操作将创建一个不正确的结构化文档(This operation would create an i

2019-07-17 16:29发布

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

Answer 1:

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


Answer 2:

您需要添加的根元素。

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


Answer 3:

在我的情况,我想不止一个的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>


文章来源: This operation would create an incorrectly structured document