2013-02-24 22 views
0

我得到這個錯誤時,當我嘗試到的XElement添加到的XDocument:InvalidOperationException異常努力的XElement添加到的XDocument

「System.InvalidOperationException」類型的異常出現在 的System.Xml。 Linq.ni.dll但在用戶代碼中處理

我的代碼是:

Imports System.Xml 
Imports System.Xml.Linq 
Imports System.IO.IsolatedStorage 
Imports System.IO 

Public Sub SaveRecord() 
     Using myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication() 

      Dim doc As XDocument 
      Using isoStore1 As IsolatedStorageFile = _ 
        IsolatedStorageFile.GetUserStoreForApplication() 

       Using isoStream1 As IsolatedStorageFileStream = New IsolatedStorageFileStream("file.xml", FileMode.Open, isoStore1) 
        doc = XDocument.Load(isoStream1) 

        MessageBox.Show(doc.ToString) 
        'This gives the right xml-code 


        doc.Add(New XElement("NewChild", "new content")) 'This is where the error takes place 
        MessageBox.Show(doc.ToString) 
        Using isoStore As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication() 

         Using isoStream As IsolatedStorageFileStream = New IsolatedStorageFileStream("file.xml", FileMode.Create, isoStore) 
          doc.Save(isoStream) 
         End Using 
        End Using 
       End Using 
      End Using 

     End Using 

     Exit Sub 

    End Sub 

錯誤顯示調試器時進入線路doc.Add(New XElement("NewChild", "new content"))

任何人都可以向我解釋這個錯誤的原因是什麼以及我如何解決它?

回答

0

您需要將您的XElement添加到您的XDocument的根。

doc.Root.Add(New XElement("NewChild", "new content")) 

直接將它添加到文檔將使您xml無效的,因爲它將是具有兩個根,因爲你是你的XDocument,而不是到根後加入XElement

相關問題