我使用以下代码验证针对Schema的XML文件。
Public Sub LoadXml(xmlFilePath As String, xsdFilePath As String)
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 List(Of String) = errorBuilder.GetErrors()
End Sub
End Class
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 List(Of String)
If _errors.Count <> 0 Then
Dim ErrorList As New List(Of String)
For i As Integer = 0 To _errors.Count - 1
Dim Message As String = _errors(i).Message
Dim LineNumber As String = _errors(i).Exception.LineNumber
Dim LinePosition As String = _errors(i).Exception.LinePosition
Dim combineString = Message & "|" & LineNumber & "|" & LinePosition
ErrorList.Add(combineString)
Next
Return ErrorList
Else
Return Nothing
End If
End Function
任何验证错误都存储在List(Of ValidationEventArgs)中,稍后由GetErrors函数处理。我的问题是Exception.LineNumber和Exception.LinePosition总是返回0.我怎样才能得到错误的行号和行位置?
答案 0 :(得分:1)
LineNumber
和LinePosition
仅在最初加载XmlDocument
时可用。如果您之后致电Validate
,他们将无法填充。原因是在加载文档之后,它已被转换为不再保持源流中的定位信息的对象图;原始的“文本”版本已被丢弃。
要在加载时进行验证,您需要执行以下操作:
Private Shared Function GetSchemaErrors(fileName As String) As List(Of XmlSchemaException)
Dim errors As New List(Of XmlSchemaException)()
Dim settings As New XmlReaderSettings()
settings.Schemas = New XmlSchemaSet()
settings.Schemas.Add(Nothing, "Path to .xsd file")
settings.ValidationType = ValidationType.Schema
AddHandler settings.ValidationEventHandler,
Sub(sender, args) errors.Add(args.Exception)
Dim reader As XmlReader = XmlReader.Create(fileName, settings)
Dim doc = New XmlDocument
doc.Load(reader)
Return errors
End Function