0

当XML和XSD都在字符串中并且确实感到困惑时,我一直在寻找简单的XML验证代码。把这件事放在一起,我希望这可以帮助别人!请随时发表评论,并指出我在哪里可能会发现这一点,告诉我在哪里可以改善这一点,或者更有效率。这将在验证失败的情况下直接写入我的错误字符串。当两个字符串都在字符串中时对XSD进行XML验证

干杯!

+0

如果遇到多个错误,它们将全部列出! – newby

回答

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 
相关问题