This operation would create an incorrectly structured document

后端 未结 3 439
忘掉有多难
忘掉有多难 2020-12-18 19:31

I am new to XML and tried the following but I\'m getting an exception. Can someone help me?

The exception is This operation would create an inc

相关标签:
3条回答
  • 2020-12-18 19:50

    You need to add root element.

    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")))));
    
    0 讨论(0)
  • 2020-12-18 20:05

    Xml document must have only one root element. But you are trying to add both Departments and Employees nodes at root level. Add some root node to fix this:

    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"))))
                    );
    
    0 讨论(0)
  • 2020-12-18 20:16

    In my case I was trying to add more than one XElement to xDocument which throw this exception. Please see below for my correct code which solved my issue

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

    Please see below for what I get in distributorInfo

    <Distributors>
     <Distributor Id="12345678" />
     <Distributor Id="22222222" />
    </Distributors>
    
    0 讨论(0)
提交回复
热议问题