Эта операция создаст неверно структурированный документ

Я новичок в 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);
}

Ответы

Ответ 1

Документ Xml должен иметь только один корневой элемент. Но вы пытаетесь добавить узлы Departments и Employees на корневом уровне. Добавьте корень node, чтобы исправить это:

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

Ответ 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")))));

Ответ 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>