如何根据 XML 架构文件验证 XML 字符串 [英] How do I validate a string of XML against an XML Schema file

查看:31
本文介绍了如何根据 XML 架构文件验证 XML 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Visual Studio 2008 在 .NET3.5 中开发 VB Web 应用程序.

I'm developing a VB Web Application in .NET3.5 using Visual Studio 2008.

在将某些 XML 添加到 HTML 表单以发布给第 3 方之前,我很难将其验证为字符串.我有一个来自第 3 方的 XML 架构文件进行验证,此时我希望应用程序在每次发布之前执行验证.

I'm having difficulty in validating some XML as a string before I add it to a HTML form to post to a 3rd party. I have an XML schema file from the 3rd party to validate against and at this point I'd like the application to perform the validation before each post.

在搜索之后,我发现了对 XmlValidatingReader 的引用,但这已经过时了,我很难找到另一种方法来做到这一点.

After searching I've found references to a XmlValidatingReader but this is obsolete and I'm having difficulty finding another way to do it.

此外,所有好的例子都在 C# 中 - 现在我坚持使用 VB.到目前为止,我正在寻求帮助!

Also all the good examples are in C# - for now I'm stuck with VB. This is what I have so far which I'm looking for help with!

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

这篇关于如何根据 XML 架构文件验证 XML 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆