是的,你在正确的轨道上。验证 XML 文档可以使用XmlDocument
或XmlReader
(稍后我将描述,您也可以使用XDocument
)。您选择哪一个将取决于您的情况,但它们的工作方式相似。当他们发现文档有错误时,他们会调用ValidationEventHandler
委托。通过对象中的XmlReader
事件调用它,XmlReaderSettings
而XmlDocument
通过作为参数传递给其Validate
方法的委托调用它。这是一个可用于收集错误的简单类:
Public Class XmlValidationErrorBuilder
Private _errors As New List(Of ValidationEventArgs)()
Public Sub ValidationEventHandler(ByVal sender As Object, ByVal args As ValidationEventArgs)
If args.Severity = XmlSeverityType.Error Then
_errors.Add(args)
End If
End Sub
Public Function GetErrors() As String
If _errors.Count <> 0 Then
Dim builder As New StringBuilder()
builder.Append("The following ")
builder.Append(_errors.Count.ToString())
builder.AppendLine(" error(s) were found while validating the XML document against the XSD:")
For Each i As ValidationEventArgs In _errors
builder.Append("* ")
builder.AppendLine(i.Message)
Next
Return builder.ToString()
Else
Return Nothing
End If
End Function
End Class
ValidationEventHandler
该类中的方法与委托的签名相匹配,ValidationEventHandler
因此您可以使用它来收集来自XmlReader
或的错误XmlDocument
。以下是您可以如何使用它XmlDocument
:
Public Function LoadValidatedXmlDocument(xmlFilePath As String, xsdFilePath As String) As XmlDocument
Dim doc As New XmlDocument()
doc.Load(xmlFilePath)
doc.Schemas.Add(Nothing, xsdFilePath)
Dim errorBuilder As New XmlValidationErrorBuilder()
doc.Validate(New ValidationEventHandler(AddressOf errorBuilder.ValidationEventHandler))
Dim errorsText As String = errorBuilder.GetErrors()
If errorsText IsNot Nothing Then
Throw New Exception(errorsText)
End If
Return doc
End Function
这里是你如何使用它XmlReader
:
Public Sub LoadXml(xmlFilePath As String, xsdFilePath As String)
Dim settings As New XmlReaderSettings()
settings.Schemas.Add(Nothing, xsdFilePath)
settings.ValidationType = ValidationType.Schema
Dim errorBuilder As New XmlValidationErrorBuilder()
AddHandler settings.ValidationEventHandler, New ValidationEventHandler(AddressOf errorBuilder.ValidationEventHandler)
Dim reader As XmlReader = XmlReader.Create(xmlFilePath, settings)
' Read the document...
Dim errorsText As String = errorBuilder.GetErrors()
If errorsText IsNot Nothing Then
' Handle the errors
End If
End Function
或者,您也可以使用较新的XDocument
类。这样做的方法XDocument
与XmlDocument
. 有一个Validate
扩展方法,XDocument
它再次需要一个ValidationEventHandler
委托。这是一个例子:
Public Function LoadValidatedXDocument(xmlFilePath As String, xsdFilePath As String) As XDocument
Dim doc As XDocument = XDocument.Load(xmlFilePath)
Dim schemas As New XmlSchemaSet()
schemas.Add(Nothing, xsdFilePath)
Dim errorBuilder As New XmlValidationErrorBuilder()
doc.Validate(schemas, New ValidationEventHandler(AddressOf errorBuilder.ValidationEventHandler))
Dim errorsText As String = errorBuilder.GetErrors()
If errorsText IsNot Nothing Then
Throw New Exception(errorsText)
End If
Return doc
End Function
至于将 XML 文档中的数据加载到数据库中,如果不知道 XML 文档的架构、数据库的架构、数据库的类型等,就不可能准确地说出如何做到这一点。我建议这样做一些关于读取 XML 数据和将数据写入数据库的研究,看看你能走多远。如果您在遇到麻烦时有任何具体问题,我们会在这里提供帮助 :)