2011-10-07 75 views
0

我想驗證xml針對XSD(VB.NET)。我的功能是這樣的:驗證xml作爲針對xsd的內存流爲字符串

​​

我該怎麼辦時,我的XML是一個MemoryStream /流驗證(我用的流,因爲我並不需要存儲的XML)和我的XSD是一個字符串(我從Web服務獲得我的xsd作爲一個字符串,我不需要將它存儲在一個文件中)?

非常感謝您的幫助!

回答

1

也許是這樣的。

Imports System.Xml 
Imports System.IO 
Imports System.Xml.Schema 

Module Module1 

    Private isvalid As Boolean 

    Sub Main() 
     Dim xml As MemoryStream 
     Dim xsd As String 
     Dim settings As New XmlReaderSettings() 
     settings.ValidationType = ValidationType.Schema 
     settings.Schemas.Add("Schema:name", xsd) 
     AddHandler settings.ValidationEventHandler, AddressOf MyValidationEventHandler 

     Dim v = XmlReader.Create(xml, settings) 

     While (v.Read()) 

     End While 

     If isValid Then 
      Console.WriteLine("Document is valid") 
     Else 
      Console.WriteLine("Document is invalid") 
     End If 
    End Sub 



    Public Sub MyValidationEventHandler(ByVal sender As Object, ByVal args As ValidationEventArgs) 
     isValid = False 
     Console.WriteLine("Validation event\n" + args.Message) 
    End Sub 
End Module 
+0

謝謝!但在行:settings.Schemas.Add(「架構:名稱」,XSD)我必須把URI的架構,我想用字符串與XSD。我怎樣才能做到這一點? – Liss

+0

在xsd字符串中,您應該有名稱空間xmlns =「urn:bookstore-schema」,您應該很容易就能知道這一點。我認爲,xsd模式名稱和xml模式名稱應該匹配,否則xml將永遠不會驗證。 – chrissie1

+0

在我的xsd中,我有xmlns:ttset =「http://www.ttset.com/or」xmlns:xs =「http://www.w3.org/2001/XMLSchema」。我應該使用什麼? – Liss