2009-04-21 73 views
2

我使用的是在开发一个.NET3.5 VB Web应用程序的Visual Studio 2008如何验证XML字符串针对XML架构文件

我有在证实一些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 

感谢

回答

3

下面是一个例子: XmlSchemaValidator in VB.NET

UPDATE - 试试这个:

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 
+0

嗨,何塞,这是一个有用的例子,但我曾看过它。我认为代码是使用XML /或模式链接的内置模式,因为它没有显示如何添加模式,是吗?此外,它仍然使用过时的XmlValidatingReader – 2009-04-21 10:19:16

1

这是我结束了

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读取它们。