VB.NET XmlDocument recursive node processing example

This is not a question but instead is an example that might be useful to someone like me who wants to study how the VB.NET XmlDocument node heirarchy works.The following subroutine recursively walks the XML document tree displaying elements and attributes as encountered...\[code\]Private Sub XmlDocumentWalker(XmlNode As XmlNode) If TypeOf XmlNode Is XmlComment Then MsgBox(XmlNode.Value, MsgBoxStyle.OkOnly, "XML Comment") If XmlNode.HasChildNodes Then XmlDocumentWalker(XmlNode.FirstChild) If Not IsNothing(XmlNode.NextSibling) Then XmlDocumentWalker(XmlNode.NextSibling) ElseIf TypeOf XmlNode Is XmlElement Then If XmlNode.HasChildNodes And (TypeOf XmlNode.FirstChild Is XmlText) Then MsgBox(XmlNode.Name & "=""" & XmlNode.FirstChild.Value & """", MsgBoxStyle.OkOnly, "XML Element") Else MsgBox(XmlNode.Name, MsgBoxStyle.OkOnly, "XML Element") End If If DirectCast(XmlNode, XmlElement).HasAttributes Then For Each XmlAttribute As XmlNode In DirectCast(XmlNode, XmlElement).Attributes MsgBox(XmlAttribute.Name & "=""" & XmlAttribute.Value & """", MsgBoxStyle.OkOnly, "XML Attribute") Next End If If XmlNode.HasChildNodes And Not (TypeOf XmlNode.FirstChild Is XmlText) Then XmlDocumentWalker(XmlNode.FirstChild) If Not IsNothing(XmlNode.NextSibling) Then XmlDocumentWalker(XmlNode.NextSibling) End IfEnd Sub\[/code\]The following code is provided to illustrate acutally loading an XML Document to be walked by the XMLDocumentWalker subroutine:\[code\]Private XmlDocument As XmlDocumentPrivate ValidationErrorCount As IntegerPublic Sub Load() ValidationErrorCount = 0 Try Dim XmlReader As XmlReader Dim XmlReaderSettings As New XmlReaderSettings() Dim ValidationEventHandler As New ValidationEventHandler(AddressOf XMLValidationErrorMessage) XmlReaderSettings.ValidationType = ValidationType.DTD XmlReaderSettings.DtdProcessing = DtdProcessing.Parse AddHandler XmlReaderSettings.ValidationEventHandler, ValidationEventHandler XmlReader = XmlReader.Create(FileName, XmlReaderSettings) XmlDocument = New XmlDocument() XmlDocument.Load(XmlReader) If 0 = ValidationErrorCount Then XmlDocumentWalker(XmlDocument) End If Catch Exception As Exception XmlDocument = Nothing MsgBox(Exception.Message, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Configuration file load error") End TryEnd SubPrivate Sub XMLValidationErrorMessage(ByVal sender As Object, ByVal args As ValidationEventArgs) If 0 = ValidationErrorCount Then MsgBox(ConfigurationResource, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Configuration file invalid") End If MsgBox(args.Message, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "XML format error") ValidationErrorCount += 1End Sub\[/code\]
 
Back
Top