2017-08-09 49 views
2

我正在使用以下代碼驗證Schema和XML文件。XML模式驗證 - 行號始終返回0

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(ValidationEventArgs)中,稍後由GetErrors函數處理。我的問題是,Exception.LineNumber和Exception.LinePosition總是返回0.我怎樣才能得到錯誤的行號和行位置?

回答

1

LineNumberLinePosition僅在最初加載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 
+0

示例代碼轉換爲VB。 –