How to generate XML file from Array of Structs
Hello,
I need assistance generating a xml file by reading values from an array of structs.
my struct looks like this:
Code:
public structure myStruct
dim ID as int
dim myArray1 as boolean
dim myArray2 as boolean
dim myArray3 as boolean
dim x as int
dim y as int
I have several instances of these structs. I also have universal variables that are declared outside of the structs. I am looking to generate a xml file like this:
Code:
<Config>
<Var1></Var1>
<Var2></Var2>
<Struct1>
<ID></ID>
<myArray1></myArray1>
<myArray2></myArray2>
<myArray3></myArray3>
<x></x>
</Struct1>
<Struct2>
<ID></ID>
<myArray1></myArray1>
<myArray2></myArray2>
<myArray3></myArray3>
<x></x>
.
.
.
</Config>
I know I can do something like:
Code:
Dim PrgXml As XElement = _
<Config>
<Var1></Var1>
<Var2></Var2>
<Struct1>
<ID></ID>
<myArray1></myArray1>
<myArray2></myArray2>
<myArray3></myArray3>
<x></x>
</Struct1>
</Config>
But how would I assign the values of each element by reading them in from the struct? Or do I need to use the XmlSerializer Class instead?
Thanks
Re: How to generate XML file from Array of Structs
Here is a model to work with. The nodes Var1 and Var2 can be done in a similar fashion as the structure more likely than not but that is something for you to work on and if you run into issues post back with the code you tried.
Code:
Option Strict On
Module Module1
Private MyList As New List(Of myStruct)
Public Structure myStruct
Dim Identifier As Integer
Dim Array1 As Boolean()
Dim Array2 As Boolean()
Dim Number1 As Integer
Dim Number2 As Integer
End Structure
Public Sub demo()
Dim Struct1 As New myStruct
Struct1.Identifier = 1
Struct1.Array1 = {False, True, False}
Struct1.Array2 = {True, True, True}
Struct1.Number1 = 1
Struct1.Number2 = 2
MyList.Add(Struct1)
Dim Struct2 As New myStruct
Struct2.Identifier = 2
Struct2.Array1 = {True}
Struct2.Array2 = {True, True, True, False, False}
Struct2.Number1 = 3
Struct2.Number2 = 4
MyList.Add(Struct2)
Dim Result =
<Config>
<%= From T In MyList Select
<Struct>
<ID><%= T.Identifier %></ID>
<Array1><%= String.Join(",", T.Array1) %></Array1>
<Array2><%= String.Join(",", T.Array2) %></Array2>
<Number1><%= T.Number1 %></Number1>
<Number2><%= T.Number2 %></Number2>
</Struct> %>
</Config>
IO.File.WriteAllText(IO.Path.Combine(Application.StartupPath, "MyFile.xml"), Result.ToString)
End Sub
End Module
The resulting file contents
Code:
<Config>
<Struct>
<ID>1</ID>
<Array1>False,True,False</Array1>
<Array2>True,True,True</Array2>
<Number1>1</Number1>
<Number2>2</Number2>
</Struct>
<Struct>
<ID>2</ID>
<Array1>True</Array1>
<Array2>True,True,True,False,False</Array2>
<Number1>3</Number1>
<Number2>4</Number2>
</Struct>
</Config>