0

当 XML 和 XSD 都在字符串中并且真的很困惑时,我一直在寻找简单的 XML 验证代码。把我发现的一些东西放在一起,希望这对其他人有帮助!请随时发表评论并指出我可能在哪里找到了这个,告诉我我可以在哪里改进这个,或者提高效率。如果验证失败,这将直接写入我的错误字符串。

干杯!

4

1 回答 1

0
Imports System
Imports System.IO
Imports System.Text
Imports System.Xml
Imports System.Xml.Schema

Module Module1

    Public validationErrors As String = Nothing
    Sub main()
        ' The Following is not a valid Xml Document according to its XSD with multiple errors.
        'Dim strXml As String = "<?xml version=""1.0"" encoding=""UTF-8""?><Address xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""><City>SuperCaliFragilisticExpiAllidocious</City><State>Confusion</State><Zipcode>16801</Zipcode></Address>"
        ' The following is a Valid XML document
        Dim strXml As String = "<?xml version=""1.0"" encoding=""UTF-8""?><Address xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""><City>Hollywood</City><State>CA</State></Address>"
        Dim strXsd As String = "<?xml version=""1.0"" encoding=""UTF-8""?><xs:schema xmlns:xs=""http://www.w3.org/2001/XMLSchema"" elementFormDefault=""qualified"" attributeFormDefault=""unqualified""><xs:element name=""Address""><xs:annotation><xs:documentation /></xs:annotation><xs:complexType><xs:sequence><xs:element name=""City""><xs:simpleType><xs:restriction base=""xs:string""><xs:maxLength value=""25""/></xs:restriction></xs:simpleType></xs:element><xs:element name=""State""><xs:simpleType><xs:restriction base=""xs:string""><xs:maxLength value=""2""/></xs:restriction></xs:simpleType></xs:element></xs:sequence></xs:complexType></xs:element></xs:schema>"
        validationErrors = xsdValidateXml(strXml, strXsd)
        MsgBox(IIf(validationErrors = Nothing, "Passed XML Validation!", validationErrors))

    End Sub
    Friend Function xsdValidateXml(ByVal strXml As String, ByVal strXsd As String)
        ' Create an XML document
        Dim xmlDocument As New XmlDocument
        xmlDocument.LoadXml(strXml)
        Dim schema As XmlReader = XmlReader.Create(New StringReader(strXsd))
        xmlDocument.Schemas.Add("", schema)
        xmlDocument.Validate(AddressOf ValidationEventHandler)
        xsdValidateXml = validationErrors
    End Function
    Sub ValidationEventHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)
        validationErrors += e.Message & vbCrLf & vbCrLf
    End Sub

End Module
于 2012-09-11T19:43:43.547 回答