2013-03-05 48 views
2

我正在嘗試找到以下函數的替代方法,該函數使用過時的System.xml.XmlValidatingReader()。我該如何適應這些代碼才能使用XMLReader,這正是Visual Studio所提出的另一種選擇?隨意在C#或VB.NET中發佈響應。我傳入函數的xmlString是引用XSD架構的原始xml。更新XmlValidatingReader函數以使用XMLReader?

'VALIDATE XML 
    Public Shared Function validateXml(ByVal xmlString As String) As XmlDocument 
     xmlErrorStr = "" 
     Dim strReader As New StringReader(xmlString) 
     Dim xmlr As New XmlTextReader(strReader) 
     Dim xmlvread As New XmlValidatingReader(xmlr) 

     ' Set the validation event handler 
     AddHandler xmlvread.ValidationEventHandler, AddressOf ValidationCallBack 

     Try 
      While (xmlvread.Read) 
      End While 
     Catch ex As Exception 
      xmlErrorStr = "<Error>" & vbCrLf & "<Exception>The XML document is invalid or malformed</Exception>" & vbCrLf & "</Error>" 
     End Try 

     'Close the reader. 
     xmlvread.Close() 
     strReader.Close() 

     Dim xmlDocument As New XmlDocument 


     xmlDocument.LoadXml("<Errors>" & xmlErrorStr & "</Errors>") 

     Return xmlDocument 
    End Function 

回答

2

只要通過適當配置​​到XmlReader.Create()方法重載之一創建驗證讀取器。有關更完整的示例,請參閱http://msdn.microsoft.com/en-ca/library/9khb6435.aspx以獲取概覽,http://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings.validationtype.aspx

+0

您的參考資料是正確的,對於我所知道的這可能就是爲什麼你的其他一些答案被低估了,或者這個答案還沒有被提高,但是在這裏,這個期望似乎是應該提供更多信息的答案 - [這個] (http://stackoverflow.com/questions/9806346/single-pass-read-and-validate-xml-vs-referenced-xsd-in-c-sharp/9812386#9812386)和[this](http:// stackoverflow.com/questions/10902908/why-is-the-xmldocument-validate-event-handler-not-getting-hit/10903288#10903288)尋找相似性很有趣... – 2013-03-25 17:27:00