0
當XML和XSD都在字符串中並且確實感到困惑時,我一直在尋找簡單的XML驗證代碼。把這件事放在一起,我希望這可以幫助別人!請隨時發表評論,並指出我在哪裏可能會發現這一點,告訴我在哪裏可以改善這一點,或者更有效率。這將在驗證失敗的情況下直接寫入我的錯誤字符串。當兩個字符串都在字符串中時對XSD進行XML驗證
乾杯!
當XML和XSD都在字符串中並且確實感到困惑時,我一直在尋找簡單的XML驗證代碼。把這件事放在一起,我希望這可以幫助別人!請隨時發表評論,並指出我在哪裏可能會發現這一點,告訴我在哪裏可以改善這一點,或者更有效率。這將在驗證失敗的情況下直接寫入我的錯誤字符串。當兩個字符串都在字符串中時對XSD進行XML驗證
乾杯!
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
如果遇到多個錯誤,它們將全部列出! – newby