I am trying to write to xml then read it. I can successfully write but when I try to read it I get the following error:
An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll
Additional information: Data at the root level is invalid. Line 1, position 1.
here is the xml file
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Settings>
<Variables>
<var_name>varsender</var_name>
<value>name@email.com</value>
</Variables>
</Settings>
here is my code:
Imports System.Xml
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim writer As New XmlTextWriter(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "\Scripts\Test\testxml.xml", System.Text.Encoding.UTF8)
createNode("varsender", "name@email.com", writer)
End Sub
Private Sub createNode(ByVal varname As String, ByVal varvalue As String, ByVal writer As XmlTextWriter)
Dim settings As XmlWriterSettings = New XmlWriterSettings()
settings.OmitXmlDeclaration = True
settings.ConformanceLevel = ConformanceLevel.Fragment
settings.CloseOutput = False
writer.WriteStartDocument(True)
writer.Formatting = Formatting.Indented
writer.Indentation = 2
writer.WriteStartElement("Settings") 'name of first element
writer.WriteStartElement("Variables")
writer.WriteStartElement("var_name")
writer.WriteString(varname)
writer.WriteEndElement()
writer.WriteStartElement("value")
writer.WriteString(varvalue)
writer.WriteEndElement()
writer.WriteEndElement()
writer.WriteEndElement()
writer.WriteEndDocument()
writer.Close()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim doc As XmlDocument = New XmlDocument()
doc.LoadXml(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "\Scripts\Test\testxml.xml")
Dim variable As String = doc.SelectSingleNode("/Settings/Variables[var_name='" & TextBox1.Text & "']/value") _
.InnerText
TextBox2.Text = variable
End Sub
End Class
the xml file doesn't have to be anything special, I am just going to be using it to store variables at close, and read the variables on open.