2012-12-29 18 views
15

मैं XML पर नया हूं और निम्नलिखित की कोशिश की लेकिन मुझे अपवाद मिल रहा है। क्या कोई मेरी मदत कर सकता है?यह ऑपरेशन गलत तरीके से संरचित दस्तावेज़ बना देगा

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 दस्तावेज़ केवल एक ही मूल तत्व होना चाहिए:

अपवाद This operation would create an incorrectly structured document

मेरे कोड है। लेकिन आप रूट स्तर पर 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")))) 
       ); 
+1

धन्यवाद 'lazyberezovsky' – Vivekh

+1

वे इस त्रुटि संदेश को और स्पष्ट बनाने के बारे में सोच सकते हैं। कुछ ऐसा है जैसे "एक्सएमएल दस्तावेज़ में केवल एक मूल तत्व हो सकता है"। इस तथ्य को जानने के बावजूद इस त्रुटि संदेश को अकेले ही समझना मुश्किल है। –

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

मेरे मामले में मैं 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(); 

कृपया मैं क्या distributorInfo

<Distributors> 
<Distributor Id="12345678" /> 
<Distributor Id="22222222" /> 
</Distributors> 
संबंधित मुद्दे