1

这不是一个问题,而是一个可能对像我这样想要研究 VB.NET 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

提供以下代码来说明实际加载要由 XMLDocumentWalker 子例程遍历的 XML 文档:

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
4

1 回答 1

0

因为这真的不是一个问题——我将其标记为已回答。

于 2012-10-03T20:58:52.370 回答