[英]How do I validate a string of XML against an XML Schema file
我正在使用Visual Studio 2008在.NET3.5中开发VB Web应用程序。
在将某些XML作为字符串验证之前,我很难将其添加到HTML表单中以发布到第三方。 我有一个来自第三方的XML模式文件来进行验证,这时我希望应用程序在每个帖子之前执行验证。
搜索之后,我发现了对XmlValidatingReader的引用,但这已经过时了,我很难找到另一种方式来做到这一点。
同样,所有好的示例都在C#中-目前,我仍然使用VB。 这是我到目前为止所寻求的帮助!
Public Function ValidateXML(ByVal strXML As String) As Boolean
' er how do I get the schema file into here?
Dim schema As XmlReader
Dim settings As XmlReaderSettings = New XmlReaderSettings()
settings.Schemas.Add("", schema)
settings.ValidationType = ValidationType.Schema
' When I use LoadXML to get the string I can't use the settings object above to get the schema in??
Dim document As XmlDocument = New XmlDocument()
document.LoadXml(strXML)
document.Validate(AddressOf ValidationEventHandler)
End Function
Private Sub ValidationEventHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)
' Gonna return false here but haven't got to it yet! Prob set a variable for use above
End Sub
谢谢
这是一个示例: VB.NET中的XmlSchemaValidator
更新 -试试这个:
Public Function ValidateXML(ByVal strXML As String) As Boolean
Dim xsdPath As String = "path to your xsd"
Dim schema As XmlReader = XmlReader.Create(xsdPath)
Dim document As XmlDocument = New XmlDocument()
document.LoadXml(strXML)
document.Schemas.Add("", schema)
document.Validate(AddressOf ValidationEventHandler)
End Function
这就是我最后要去的
Public validationErrors As String = ""
Public Function ValidPortalRequest(ByVal XMLPortalRequest As String) As Boolean
Try
Dim objSchemasColl As New System.Xml.Schema.XmlSchemaSet
objSchemasColl.Add("xxx", "xxx")
objSchemasColl.Add("xxx", "xxxd")
Dim xmlDocument As New XmlDocument
xmlDocument.LoadXml(XMLPortalRequest)
xmlDocument.Schemas.Add(objSchemasColl)
xmlDocument.Validate(AddressOf ValidationEventHandler)
If validationErrors = "" Then
Return True
Else
Return False
End If
Catch ex As Exception
Throw
End Try
End Function
Private Sub ValidationEventHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)
validationErrors += e.Message & "<br />"
End Sub
与Jose相同,除了我添加了2个XSD作为SchemaSet而不是使用XMLReader读取它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.