XmlWriter Not Creating New Element in VB.net
I'm writing out an XML file using VB.net. When I try to create another element to be written past the fir开发者_如何学JAVAst, 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
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.
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
精彩评论