Sì, siete sulla strada giusta. La convalida di un documento XML può essere eseguita utilizzando o XmlReader
(come descritto più avanti, è possibile utilizzare anche XDocument
). Quale sceglierai dipenderà dalla tua situazione, ma entrambi funzionano allo stesso modo. Quando trovano un errore nel documento, chiamano un delegato ValidationEventHandler
. Lo XmlReader
lo chiama tramite un evento nell'oggetto XmlReaderSettings
mentre lo lo chiama tramite un delegato passato come parametro al suo metodo Validate
. Ecco una semplice classe che può essere utilizzato per raccogliere gli errori:
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 Sub
End Class
Il metodo ValidationEventHandler
in quella classe corrisponde la firma del ValidationEventHandler
delegato, quindi è possibile utilizzarlo per raccogliere gli errori sia dal XmlReader
o XmlDocument
. Ecco come è possibile utilizzare con il 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
Ed ecco come è possibile utilizzare con il 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
In alternativa, è anche possibile utilizzare la nuova classe XDocument
. Il modo per farlo con XDocument
è molto simile a XmlDocument
. Esiste un metodo di estensione Validate
per lo XDocument
che accetta, ancora una volta, un delegato ValidationEventHandler
. Ecco un esempio di che:
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
Per quanto riguarda il caricamento dei dati del documento XML in un database, è impossibile dire come, appunto, di farlo senza conoscere lo schema del documento XML, lo schema del database, il tipo di database, ecc. Consiglierei di fare qualche ricerca sia per leggere i dati XML e scrivere i dati nei database e vedere quanto lontano si ottiene. Se hai domande specifiche in caso di problemi, saremo qui per aiutarti :)
possibile duplicato di [Come convalidare XML contro Schema in VB.net] (http://stackoverflow.com/questions/ 15088585/how-to-validate-xml-contro-schema-in-vb-net) –