1

当我尝试将 XElement 添加到 XDocument 时出现此错误:

System.Xml.Linq.ni.dll 中出现“System.InvalidOperationException”类型的异常,但未在用户代码中处理

我的代码是:

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"))

谁能向我解释这个错误的原因是什么以及我该如何解决?

4

1 回答 1

2

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

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

将其直接添加到文档将使您xml无效,因为它将有两个根,因为您将XElement在您的后面添加XDocument而不是添加到根。

于 2013-02-24T22:14:09.757 回答