2012-12-29 29 views
15

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

讓你有什麼錯誤我正確的代碼? –

回答

21

XML文檔必須只有一個根元素。但是您正試圖在根級別添加DepartmentsEmployees節點。添加一些根節點來解決這個問題:

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

感謝'lazyberezovsky' – Vivekh

+1

他們可能會考慮使這個錯誤消息更明確。像「XML文檔可能只有一個根元素」。即使知道這個事實,單靠這個錯誤信息也很難理解這個問題。 –

11

您需要添加根元素。

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

在我的情況下,我試圖添加多個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>