gpt4 book ai didi

XML 架构验证 - 行号始终返回 0

转载 作者:行者123 更新时间:2023-12-02 05:51:24 26 4
gpt4 key购买 nike

我正在使用以下代码根据架构验证 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。如何获取错误的行号和行位置?

最佳答案

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

关于XML 架构验证 - 行号始终返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45585471/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com