尝试将XElement添加到XDocument时出现InvalidOperationException

时间:2013-02-24 22:05:24

标签: vb.net linq-to-xml windows-phone-8

当我尝试将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"))

时,会显示错误

任何人都可以向我解释这个错误的原因是什么以及如何解决它?

1 个答案:

答案 0 :(得分:1)

您需要将XElement添加到XDocument的根目录。

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

将其直接添加到文档会使xml无效,因为它会在您的XElement之后添加XDocument而不是根目录。