2012-12-29 34 views
15

Tôi mới đến XML và đã thử làm như sau nhưng tôi nhận được ngoại lệ. Ai đó có thể giúp tôi?Thao tác này sẽ tạo tài liệu có cấu trúc không chính xác

Trường hợp ngoại lệ là This operation would create an incorrectly structured document

Mã của tôi:

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); 
} 
+0

lỗi gì bạn có? –

Trả lời

21

tài liệu Xml phải chỉ có một phần tử gốc. Nhưng bạn đang cố gắng thêm cả hai nút DepartmentsEmployees ở cấp cơ sở. Thêm một số nút gốc để sửa lỗi này:

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

Cảm ơn 'lazyberezovsky' – Vivekh

+1

Họ có thể nghĩ đến việc làm cho thông báo lỗi này rõ ràng hơn. Một cái gì đó như "tài liệu XML có thể chỉ có một phần tử gốc". Ngay cả khi biết thực tế này, thật khó để hiểu được vấn đề bằng thông báo lỗi này một mình. –

11

Bạn cần thêm phần tử gốc.

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

Trong trường hợp của tôi, tôi đã cố gắng thêm nhiều hơn một XElement vào xDocument để loại trừ ngoại lệ này. Xin vui lòng xem dưới đây để biết mã chính xác của tôi mà giải quyết vấn đề của tôi

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

Xin xem dưới đây để biết những gì tôi nhận được trong distributorInfo

<Distributors> 
<Distributor Id="12345678" /> 
<Distributor Id="22222222" /> 
</Distributors> 
Các vấn đề liên quan