是的,您走在正确的道路上。验证 XML 文档可以使用以下任一方法完成XmlDocument
or 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
The ValidationEventHandler
该类中的方法与ValidationEventHandler
委托,因此您可以使用它来收集来自XmlReader
or the 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 数据和将数据写入数据库的研究,看看您能走多远。如果您遇到麻烦时有任何具体问题,我们将随时为您提供帮助:)