XmlException: Node used in a document that did not create it

Hello

I’m trying to save a file in a xmldocument, my code exists of many different object, and I want to save them in 1 document. I got an error on this piece of code:

EventsXML = root.AppendChild(Xml.CreateElement("events")) For Each E As ControlEvent In Events.Values Try EventXML = EventsXML.AppendChild(E.SaveToXML) Catch ex As XmlException MsgBox(ex.Message) End Try Next

And the code of ControlEvent.SaveToXML is:

[code] Dim Xml As New XmlDocument
Dim root As xmlNode

root = xml.AppendChild(Xml.CreateElement(“controlevent”))
root.SetAttribute(“name”, Name)
root.SetAttribute(“checked”, Cstr(Checked))

Return Xml[/code]

I ran into a Hierarchy request error.
I figured it out that was maybe because I tried to nest a XmlDocument in a XmlDocument, so I tried to change the last line of the last piece of code into

Return root

But than I got the “XmlException: Node used in a document that did not create it” error. What is the proper way to nest an XmlNode from a function in another XmlNode?

Thanks in advance.

You need to call ImportNode to import the returned node into the main document so it will look like the current document created it. It will end up looking something like:

EventsXML = root.AppendChild(Xml.CreateElement("events"))
  For Each E As ControlEvent In Events.Values
    Try
      Dim n as XMLNode = xml.ImportNode(E.SaveToXML.FirstChild) 'or just E.SaveToXML if you return a node
      EventXML = EventsXML.AppendChild(n)
    Catch
...

The ImportNode docs have a little more info.

Thanks Mr Gookin

Stupid of me, I should’ve checked the docs better.

I spent way more time with XMLDocument than I wanted learning why it didn’t work the way I thought it would. :slight_smile: