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 ドキュメントにはルート要素が 1 つだけ含まれている必要があります。しかし、ルート レベルで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();

私がディストリビューター情報で取得するものについては、以下を参照してください

<Distributors>
 <Distributor Id="12345678" />
 <Distributor Id="22222222" />
</Distributors>
于 2014-12-02T19:36:33.460 に答える