.NET compare XML object vs. Schema?

Kyle.Allbright

Active member
Joined
Apr 19, 2010
Messages
28
Programming Experience
1-3
Hey All - I am attempting to compare an XML document that I have created via code against a schema for validation before exporting my XML document.

I have been able to save the document to the HD, and then run it against the schema - however - is there a way that I can compare the object that has been generated through code directly with a schema? (i.e keep the xml in memory)

Here is my current code:

VB.NET:
 Public Shared Function Validate(ByVal xmlDocument As String) As Boolean

        AltovaXMLValidator()
        'First we create the xmltextreader

        Dim xmlReader As New XmlTextReader(xmlDocument)

        'Pass the XmlReader into the XmlValidationReader to validate the xml document against the schema
        Dim validationReader As New XmlValidatingReader(xmlReader)

        AddHandler validationReader.ValidationEventHandler, AddressOf ValidationCallBack

        isValid = True

        While (validationReader.Read)
        End While

        validationReader.Close()

        Return isValid
    End Function

Note: I know I am using an obsolete class currently.
 
Another example using LINQ to XML: How to: Validate Using XSD (LINQ to XML)

Since you've listed yourself as .NET 4.0 you may want to ditch the XSDErrors delegate function for something closer to this. (Hand typed so the syntax may be slightly off.)

VB.NET:
errors = False
doc1.Validate(schemas, Function(sender, e) Do
     Console.WriteLine(e.Message)
     errors = True
End Function, True)
Console.WriteLine("Document {0}", If(errors, "failed validation", "validated")
 
Back
Top