' Collection of code snippets by Arne Vajhøj 
' (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
﻿Imports System
Imports System.IO
Imports System.Xml

Namespace XmlProc.W3CDOM
    Public Class Program
        Private Const XML_FILE As String = "C:\work\employees.xml"
        Public Shared Sub Main(args As String())
            ' read from file to DOM tree
            Dim doc As New XmlDocument()
            doc.Load(XML_FILE)
            ' iterate over all employee elements
            For Each employee As XmlElement In doc.DocumentElement.GetElementsByTagName("employee")
                ' find attribute no
                Dim no As String = employee.Attributes("no").Value
                ' find sub elements name and role
                Dim name As String = ""
                Dim role As String = ""
                For Each child As XmlNode In employee.ChildNodes
                    If child.NodeType = XmlNodeType.Element AndAlso child.Name = "name" Then
                        name = child.FirstChild.Value
                    End If
                    If child.NodeType = XmlNodeType.Element AndAlso child.Name = "role" Then
                        role = child.FirstChild.Value
                    End If
                Next
                ' print
                Console.WriteLine("no = " & no)
                Console.WriteLine("name = " & name)
                Console.WriteLine("role = " & role)
            Next
            ' add employee
            Dim newname As XmlElement = doc.CreateElement("name")
            newname.AppendChild(doc.CreateTextNode("Dave D"))
            Dim newrole As XmlElement = doc.CreateElement("role")
            newrole.AppendChild(doc.CreateTextNode("Intern"))
            Dim newemployee As XmlElement = doc.CreateElement("employee")
            Dim newno As XmlAttribute = doc.CreateAttribute("no")
            newno.Value = "4"
            newemployee.Attributes.Append(newno)
            newemployee.AppendChild(newname)
            newemployee.AppendChild(newrole)
            doc.DocumentElement.AppendChild(newemployee)
            ' write out
            Using sw As New StreamWriter("C:\work\employees2.xml")
                doc.Save(sw)
            End Using
        End Sub
    End Class
End Namespace
