.NET Framework - validating if a file is a true valid xml file that fits a certain schema

Asked By Andy B
29-Jun-08 09:09 PM
I need to make sure that a file saved in a particular place is a valid xml
file that fits a certain schema. Where would I get started doing this? The
original file would have been created and saved with a dataset.
ValidationEventHandler
(1)
XmlSchemaException
(1)
XmlSchemaSet
(1)
ApplicationException
(1)
Callback
(1)
Stream
(1)
ValidationEventArgs
(1)
XmlReaderSettings
(1)
  Cor Ligthert[MVP] replied...
29-Jun-08 11:33 PM
Andy,

Just set it in a Try and Catch block with a dataset.ReadXML

Cor
  rowe_newsgroups replied...
01-Jul-08 06:57 AM
l
e

Replies to this in your other thread:

http://groups.google.com/group/microsoft.public.dotnet.languages.vb/browse_=
thread/thread/cf1b61b8b513dfbc

Thanks,

Seth Rowe [MVP]
http://sethrowe.blogspot.com/
  surtur replied...
30-Jun-08 10:23 PM
It's pretty fiddly, here's my code:

''' <summary>
''' Validates an XML stream against the specified XML Schema. Raises
ValidateXmlFileException if the XML stream or XML Schema fails validation.
''' </summary>
''' 
''' 
''' 
''' <exception cref="ValidateXMLFileException">Raised if XML or XML
File fails validation</exception>
''' <remarks></remarks>
Public Sub ValidateXmlFile(ByVal SchemaNamespace As String, ByVal
SchemaStream As Stream, ByVal XmlStream As Stream)

' Create the XmlSchemaSet class.
Dim sc As XmlSchemaSet = New XmlSchemaSet()

Try
' Add the schema to the collection.
Dim xrInput As New XmlTextReader(SchemaStream)
sc.Add(SchemaNamespace, xrInput)

' Set the validation settings.
Dim settings As XmlReaderSettings = New XmlReaderSettings()
settings.ValidationType = ValidationType.Schema
settings.Schemas = sc
AddHandler settings.ValidationEventHandler, AddressOf
ValidateXmlFile_Callback
' Create the XmlReader object.
Using reader As XmlReader = XmlReader.Create(XmlStream,
settings)
' Parse the file.
Do While reader.Read() : Loop
End Using
If mstrValidateXmlFileErrorMessage > "" Then
Throw New ValidateXMLFileException("The XML Stream
failed validation", New ApplicationException(mstrValidateXmlFileErrorMessage))
End If
RemoveHandler settings.ValidationEventHandler, AddressOf
ValidateXmlFile_Callback
Catch ex As XmlSchemaException
Throw New ValidateXMLFileException("Could not parse schema",
ex)
Catch ex As XmlException
Throw New ValidateXMLFileException("Could not parse XML", ex)
End Try

End Sub
Private Sub ValidateXmlFile_Callback(ByVal sender As Object, ByVal e
As ValidationEventArgs)
mstrValidateXmlFileErrorMessage = e.Message
End Sub
Public Class ValidateXMLFileException
Inherits Exception
Sub New(ByVal ErrorMessage As String, ByVal InnerException As
Exception)
MyBase.New(ErrorMessage, InnerException)
End Sub
End Class

--
David Streeter
Synchrotech Software
Sydney Australia
  Cor Ligthert[MVP] replied...
30-Jun-08 11:35 PM
SuturZ,

Can you explain what it does more then my simple line of code in a Try and
Catch?

Cor
  surtur replied...
01-Jul-08 01:10 AM
My code tests against a supplied XML Schema.

I don't know if Dataset.ReadXML does that. I've never used Dataset.ReadXML
though, perhaps it is a better approach.

BTW I think in my original post I missed a module level String variable
declaration:

Private mstrValidateXmlFileErrorMessage As String 'used by ValidateXmlFile()

--
David Streeter
Synchrotech Software
Sydney Australia
  surtur replied...
01-Jul-08 10:01 PM
I just had a play around with the Dataset XML functions. They are VERY good,
and are the better solution for the OP.

However, they seem to work only for XML/XSDs that have been generated from a
Dataset. If you are sourcing your XML/XSD from a different source, then my
code might be necessary (it can validate any XML file against any schema).

--
David Streeter
Synchrotech Software
Sydney Australia
Create New Account
help
Howto use callback functions with a C DLL .NET Framework I have a C DLL that I want typedef void (*callback_t) (const unsigned char *data, unsigned int size, void *userdata); void myfunction (callback_t callback, void *userdata); How do I translate this to C#? I tried with: delegate void callback_t (Byte[] data, UInt32 size, IntPtr userdata); [DllImport("mydll.dll")] static extern void myfunction (callback_t callback, IntPtr userdata); When calling with myfunction (null, IntPtr.Zero) everything works as expected. But once I start passing a callback function, the application crashes with "Unhandled Exception: System.AccessViolationException: Attempted to read or write protected other memory is corrupt." void test (Byte[] data, UInt32 size, IntPtr userdata) { / / Nothing here } callback_t callback = new callback_t (test); myfunction (callback, IntPtr.Zero); I tried changing the data parameter from a byte array to an IntPtr seems to make no difference. What am I doing wrong? All other functions (without a callback function parameter) work perfect. C# Discussions AccessViolationException (1) CallingConvention.Cdecl (1) Console.WriteLine (1) CallingConvention IntPtr (1) Console (1) UnmanagedFunctionPointer (1) Jef, What is the C code doing with the callback data and how is it calling the callback? - - - Nicholas Paldino [.NET / C# MVP] - mvp@spam
CallBack. .NET Framework Hola, Estoy intentando comunicarme con una DLL donde tengo que implementar un callback. Es decir, a una función de inicialización debo pasarle dos parametros de funciones que en problema es que no se activan y no se exactamente si estoy realizando correctamente el callback. el código que tengo es el siguiente: HINSTANCE hSemiautonomoDll; void (*call_back)(void); void (*call_back_impresion)(void EMV_procesar_datos_impresora; / * Hago la llamada a la función de la DLL pasando las dos funciones de callback * / Local_Inicializar(call_back , call_back_impresion , &KE_datos); Las funciones que se deberian activar son: void EMV_procesar_datos_impresora (void) { } void void), void (*llamada_impresion)(void), datos_intercambio * datos); Estoy declarandolo correctamente ??? Gracias. VC - Spanish Discussions DLL (1) CallBack (1) KE_INICIALIZAR (1) HSemiautonomoDll (1) EMV_procesar_datos_respuesta (1) EMV_procesar_datos_impresora (1) Local_Inicializar (1) KE_datos (1) On Thu direcciones a llamar. Además, tienes que ver en qué protocolo de llamada están los dos callback. Si quien ha hecho la DLL lo ha hecho bien (para que funcione en cualquier DLL debe abrir un puerto serie. Esto lo hace, y despues activar la función de callback - esto no lo hace. La gente que ha hecho la DLL me indica que le entiendo, porque creo que no. Quizas no estoy haciendo correctamente la espera del evento de callback? Lo estoy haciendo esperando en un bucle infinito. Así me puede saltar el evento ? En
Can I throw an exception from my managed callback? .NET Framework I'm using the ETW functions, OpenTrace(), ProcessTrace(), and CloseTrace(). ProcessTrace() opens an ETL file and enumerates the events in the file and calls a callback for each event. I'm calling these interop calls from C# and my callback is in C#. In this callback if I encounter an exception I'm letting it be thrown back into the unmanaged being reflected in the return code from ProcessTrace(). When I throw an exception in my callback ProcessTrace() still return SUCCESS. Is this the expected behavior? Is it OK to throw exceptions the issue about how to make the ProcessTrace API return corresponding error code, when managed callback function throws an exception. I appreciate your patience. Besides, could you please let me know and provide you with a possible workaround. Based on the MSDN documentation, if the native callback function throws an exception, the ProcessTrace API returns ERROR_NOACCESS (Code: 998, Message: Invalid access to ms681388.aspx. Based on my research on the managed codes, if the exception in managed callback function is caught inside the callback function, the ProcessTrace function returns zero (SUCCESS). If the
Problem with ValidationEventHandler .NET Framework Hi I've got a xml file and xsd with only one namespace or xmlns:yt. When I'm trying to validate this Xml with my xsd the validationeventhandler show me only the first error. But what when we got xml file like: . . . . The to show me all the errors?? Thanks kplazinski Xml Discussions XmlSchemaValidationFlags.ReportValidationWarnings (1) XmlSchemaValidationFlags (1) ValidationEventHandler (1) XmlSchemaSet (1) ValidationType.Schema (1) XmlReader.Create (1) Server.MapPath (1) StreamReader (1) Can you show JavaScript.FAQTs.com / It's something about this: protected void Page_Load(object sender, EventArgs e) { XmlSchemaSet set = new XmlSchemaSet(); set.Add(null, Server.MapPath("rss.xsd")); set.Add(null, Server.MapPath("mediarss.xsd")); XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas = set; settings.ValidationEventHandler + = new ValidationEventHandler(settings_ValidationEventHandler); settings.ValidationFlags | = XmlSchemaValidationFlags.ReportValidationWarnings; StreamReader sreader = new StreamReader(Server.MapPath("file.xml")); XmlReader xreader
assertion", "c: \ oasis-sstc-saml-schema-protocol-1.1.xsd"); settings.ValidationType = ValidationType.Schema; settings.ValidationEventHandler + = delegate(object sender, ValidationEventArgs e) { isValid = false; }; XmlReader reader = XmlReader.Create(new StringReader(AssertionXML), settings DTD while normal settings since .NET 2.0 disable DTD processing. So to have the XmlSchemaSet process that schema you need to load it explicitly with an XmlReader and XmlReaderSettings having ProhibitDtd as false. Otherwise the XmlSchemaSet does not compile and throws that exception you see. For better error messages / diagnostics you might want to set up a ValidationEventHandler on the Schemas property of your XmlReaderSettings, that way you get a warning that the new XmlReaderSettings(); dtdSettings.ProhibitDtd = false; XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas.ValidationEventHandler + = delegate(object sender, ValidationEventArgs vargs) { Console.WriteLine("Schema problem: Line {2}: {0}: {1}", vargs.Severity xsd", dtdSettings)); settings.Schemas.Add(null, @". . \ . . \ XMLSchema1.xsd"); settings.Schemas.Add(null, @". . \ . . \ XMLSchema2.xsd"); settings.ValidationEventHandler + = delegate(object sender, ValidationEventArgs vargs) { Console.WriteLine("{0}: {1}", vargs.Severity, vargs.Message); }; using (XmlReader schemas will be loaded with the same settings and that way the import and the XmlSchemaSet compilation works so that you will get the validation error then for your XML document new XmlReaderSettings(); dtdSettings.ProhibitDtd = false; XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas.ValidationEventHandler + = delegate(object sender, ValidationEventArgs vargs) { Console.WriteLine("Schema problem: Line {2}: {0}: {1}", vargs.Severity