Use the XmlWriter type to generate an XML file in a For-Each loop.
XmlWriter generates an XML document using code. There are several ways to do this. But the XmlWriter type is one of the oldest and most reliable ways. We formulate a reliable way to generate XML files in the VB.NET language.XmlReaderFile
Example. We introduce the Employee class, which has four fields that store instance data, and the Main entry point subroutine, which writes the XML file. The Employee class holds the ID, first name, last name, and salary of each employee.Sub
Next: The XmlWriterSettings dim is created. We do this to ensure that the resulting XML file will have whitespace and will be readable.
WriteStartDocument: WriteStartDocument and root element. Next the WriteStartDocument subroutine is invoked.
And: This writes the header line of the XML file to the disk. The root element <Employees> is then created.
For-Each: Elements are written with all the values from the fields in the Employee class. After the For Each terminates, the document is ended.
VB.NET program that uses XmlWriter
''' Employee type.
Public Sub New(ByVal id As Integer, ByVal firstName As String, _
ByVal lastName As String, ByVal salary As Integer)
' Set fields.
Me._id = id
Me._firstName = firstName
Me._lastName = lastName
Me._salary = salary
' Storage of employee data.
Public _firstName As String
Public _id As Integer
Public _lastName As String
Public _salary As Integer
' Create array of employees.
Dim employees(2) As Employee
employees(0) = New Employee(1, "Prakash", "Rangan", 70000)
employees(1) = New Employee(5, "Norah", "Miller", 21000)
employees(2) = New Employee(17, "Cecil", "Walker", 60000)
' Create XmlWriterSettings.
Dim settings As XmlWriterSettings = New XmlWriterSettings()
settings.Indent = True
' Create XmlWriter.
Using writer As XmlWriter = XmlWriter.Create("C:\employees.xml", settings)
' Begin writing.
writer.WriteStartElement("Employees") ' Root.
' Loop over employees in array.
Dim employee As Employee
For Each employee In employees
' End document.
<?xml version="1.0" encoding="utf-8"?>
Discussion. There are some improvements you can make to this program. You could change the Employee class to use properties instead of public fields. This can sometimes create more useful abstractions for object-oriented designs.Property
Also: The data inside the employee array could be acquired from another data source, such as a Windows Forms control or a database server.
Summary. The XmlWriter type introduces an abstract data type in the VB.NET language and .NET Framework that makes generating XML files much easier. You could just manually print out the XML file. But this usually results in confusing code.
Tip: With the right level of abstraction, a type such as XmlWriter can make your life easier.