1
這不是一個問題,而是一個可能對像我這樣想研究VB.NET XmlDocument節點層次結構如何工作的人有用的示例。XmlDocument遞歸節點處理示例
下面的子過程遞歸遍歷XML文檔樹顯示元素和屬性遇到...
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 If
End Sub
下面的代碼提供給真正說明加載XML文檔由XMLDocumentWalker子程序走:
Private XmlDocument As XmlDocument
Private ValidationErrorCount As Integer
Public 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 Try
End Sub
Private 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 += 1
End Sub
你可以回答你自己的問題,但只有當你第一次_ask_它。 –