当我尝试将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 :(得分:1)
您需要将XElement
添加到XDocument
的根目录。
doc.Root.Add(New XElement("NewChild", "new content"))
将其直接添加到文档会使xml
无效,因为它会在您的XElement
之后添加XDocument
而不是根目录。