2012-12-29 10 views
15

Sono nuovo a XML e ho provato quanto segue, ma ricevo un'eccezione. Qualcuno può aiutarmi?Questa operazione creerebbe un documento strutturato in modo errato

L'eccezione è This operation would create an incorrectly structured document

Il mio codice:

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

Quale errore avete? –

risposta

21

documento XML deve avere un solo elemento radice. Ma stai cercando di aggiungere entrambi i nodi Departments e Employees a livello di root. Aggiungi un nodo root per risolvere il problema:

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

Grazie 'lazyberezovsky' – Vivekh

+1

Potrebbero pensare di rendere questo messaggio di errore più esplicito. Qualcosa come "documento XML può avere solo un elemento radice". Pur conoscendo questo fatto è difficile capire il problema solo da questo messaggio di errore. –

11

È necessario aggiungere l'elemento radice.

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

Nel mio caso stavo cercando di aggiungere più di un XElement a XDocument che lanciare questa eccezione. Vedi sotto per il mio codice corretto che ha risolto il mio problema

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

prega di vedere sotto per quello che ho entrare in distributorInfo

<Distributors> 
<Distributor Id="12345678" /> 
<Distributor Id="22222222" /> 
</Distributors> 
Problemi correlati