views:

801

answers:

2

I'm writing out an XML file using VB.net. When I try to create another element to be written past the first, it errors out saying:

"Token StartElement in state EndRootElement would result in an invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment."

I'm not sure why it is doing this considering that the previous element has been closed. I tried to look for a writer.WriteEndRootElement, but I didn't see any in there. Any suggestions to get it to work? =)

    Private Sub writeXMLFile(ByVal childform As Fone_Builder_Delux.frmData, ByVal filename As String)

        Dim xmlSettings As New XmlWriterSettings()
        xmlSettings.Indent = True
        xmlSettings.NewLineOnAttributes = True

        Using writer As XmlWriter = XmlWriter.Create(filename, xmlSettings)

            writer.WriteStartDocument()
            writer.WriteStartElement("header")

            writer.WriteStartAttribute("filepath")
            writer.WriteValue(filename)
            writer.WriteEndAttribute()

            writer.WriteEndElement()
            writer.WriteStartElement("variable")
            writer.WriteStartAttribute("varName")

            writer.WriteValue(childform.datagridHeaders.Item(0, 1))

            writer.WriteEndAttribute()
            writer.WriteEndElement()
            writer.WriteEndDocument()
            writer.Flush()

        End Using


    End Sub
+2  A: 

An XML document can have only one root element. You are starting the document, writing the "header" element, closing the "header" element, then starting a new "variable" element -- which would be a second root element.

Either enclose both "header" and "variable" within a single higher-level element, or move one of them inside the other.

itowlson
Thank you, I didn't realize that about XML files. I'll probably enclose them inside one master element. Thanks!
Dropped.on.Japan
A: 

You can try something like this

 Private Sub writeXMLFile(ByVal childform As Fone_Builder_Delux.frmData, ByVal filename As String)

    Dim xmlSettings As New XmlWriterSettings()
    xmlSettings.Indent = True
    xmlSettings.NewLineOnAttributes = True

    Using writer As XmlWriter = XmlWriter.Create(filename, xmlSettings)

        writer.WriteStartDocument()
        writer.WriteStartElement("root")
        writer.WriteStartElement("header")

        writer.WriteStartAttribute("filepath")
        writer.WriteValue(filename)
        writer.WriteEndAttribute()

        writer.WriteEndElement()
        writer.WriteStartElement("variable")
        writer.WriteStartAttribute("varName")

        writer.WriteValue(childform.datagridHeaders.Item(0, 1))

        writer.WriteEndAttribute()
        writer.WriteEndElement()
        writer.WriteEndElement()
        writer.WriteEndDocument()
        writer.Flush()

    End Using


End Sub
madan