26

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

3 回答 3

35

XML 文档必须只有一个根元素。但是您正在尝试在根级别添加Departments和节点。Employees添加一些根节点来解决这个问题:

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"))))
                );
于 2012-12-29T12:52:33.493 回答
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")))));
于 2012-12-29T12:55:18.053 回答
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>
于 2014-12-02T19:36:33.460 回答