I am trying to build an XML file, where I generate a variable type XmlTextWriter in the main class, to be able to read it globally. Then, inside a NavButton, I create a new variable with the same name and send it the path attribute so that it generates the file within a specific path.
When I get to the conditional if it is TRUE, it enters the function and sends 4 parameters, which the function receives correctly, but when it starts to write inside the XML, it does not send an error and continues fine, but when opening the XML already when finished, is empty and only with two lines.
I understand that you would be talking about two variables with the same name, but one global and one local and both have different paths.
My question is, how can I update the attribute or path of the global variable, from the local one and pass it the correct path so that the function writes in the XML that it should be?
This is my code:
Public Class Form1
Dim path As String = "0"
Dim writerC As New XmlTextWriter(path, System.Text.Encoding.UTF8)
End Class
Private Sub NavButton1_ElementClick(sender As Object, e As NavElementEventArgs) Handles NavButton1.ElementClick
Dim pathRoot as String = "C:\Temp"
Dim strPathC As String = pathRoot & "\" & "e" & TextBox1.Text & ".XML"
Dim writerC As New XmlTextWriter(strPathC, System.Text.Encoding.UTF8)
writerC.WriteStartDocument(True)
writerC.Formatting = Formatting.Indented
writerC.Indentation = 2
writerC.WriteStartElement("PageCollection") '---PageCollection---
if i = 0 then
sheetTest("A", "B", "C", "D")
end if
writerC.WriteEndElement() '---PageCollection/---
writerC.Close() '---CLOSING XML FILE/---
pathRoot = pathRoot & "\" & "SentFiles"
Directory.CreateDirectory(pathRoot)
MsgBox("Successfully generated files.", MsgBoxStyle.Information MessageBoxButtons.OK, "TEST")
End Sub
Public Function sheetTest(firstParameter as string, secondParameter as string, thirdParameter as string, fourthParameter as string)
writerC.WriteStartElement("Page") '---Page---
writerC.WriteStartElement("Collection") '---Collection---
writerC.WriteEndElement() '---Collection/---
writerC.WriteEndElement() '---Page/---
End Function
Thanks for your time. Regards.
CodePudding user response:
Due to how variable scoping works, you are declaring two different variables with identical names (writerC), but different scopes.
Try this:
Public Class Form1
Dim path As String = "0"
Dim writerC As XmlTextWriter
End Class
Private Sub NavButton1_ElementClick(sender As Object, e As NavElementEventArgs) Handles NavButton1.ElementClick
writerC = New XmlTextWriter(strPathC, System.Text.Encoding.UTF8)
End Sub