|
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
Note: This is an unedited contribution. If this article is inappropriate,
needs attention or copies someone else's work without reference then please
Report This Article
IntroductionObjective: Validating an Object with Xml Schema Steps to follow: 1. Serialize that object to xml document 2. Validate that Xml document with Xml Schema using XmlValidator class. BackgroundSerialization: Serialization is the process of converting the state of an object into a form that can be persisted or transported. The complement of serialization is de-serialization, which converts a stream into an object. Together, these processes allow data to be easily stored and transferred. The .NET Framework features two serializing technologies: · Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share an object between different applications by serializing it to the Clipboard. You can serialize an object to a stream, to a disk, to memory, over the network, and so forth. Remoting uses serialization to pass objects "by value" from one computer or application domain to another. · XML serialization serializes only public properties and fields and does not preserve type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data. Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is likewise an open standard, which makes it an attractive choice. Using the codeExample on Xml Serialization VALIDATING XML THROUGH SCHEMA //ValidateXml method Validates an Xml content with related Schema. private static bool ValidateXml(string XmlizedString) { XmlTextReader schemaTextReader = null; XmlSchemaCollection schemaCollection = null; XmlValidatingReader validationReader = null; //Adding Schemas to SchemaCollection string schemaPath1 = ConfigurationSettings.AppSettings["SchemaPath1"]; string schemaPath2 = ConfigurationSettings.AppSettings["SchemaPath2"]; schemaTextReader = new XmlTextReader(schemaPath1); schemaCollection = new XmlSchemaCollection(); schemaCollection.Add(null, schemaTextReader); schemaTextReader = new XmlTextReader(schemaPath2); schemaCollection.Add(null, schemaTextReader); // XML validator object validationReader = new XmlValidatingReader(XmlizedString, XmlNodeType.Document, null); validationReader.Schemas.Add(schemaCollection); // Add validation event handler validationReader.ValidationType = ValidationType.Schema; validationReader.ValidationEventHandler += new ValidationEventHandler(reader_ValidationEventHandler); // Validate XML data while (validationReader.Read()) ; validationReader.Close(); // Raise exception, if XML validation fails if (ErrorsCount > 0) { throw Exception(ErrorMessage); } else { return true; } return false; } //Method will be invoked when Validation Event invoked. public static void reader_ValidationEventHandler(object sender, ValidationEventArgs args) { ErrorMessage = ErrorMessage + args.Message.ToString() + "\r\n"; ErrorsCount++; } //Method to convert given object to Xml String public static string SerializeToXML(object responseObject) { //DefaultNamespace of XSD //We have to Namespace compulsory, if XSD using any namespace. XmlSerializer xmlObj = new XmlSerializer(responseObject.GetType(), "namespace"); String XmlizedString = null; MemoryStream memoryStream = new MemoryStream(); XmlTextWriter XmlObjWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); XmlObjWriter.Formatting = Formatting.Indented; xmlObj.Serialize(XmlObjWriter, responseObject); memoryStream = (MemoryStream)XmlObjWriter.BaseStream; UTF8Encoding encoding = new UTF8Encoding(); XmlizedString = encoding.GetString(memoryStream.ToArray()); XmlObjWriter.Close(); XmlizedString = XmlizedString.Substring(1); return XmlizedString; } Note : If you have any Complex Type elements, declare elements for complextypes. Otherwise, it will throw an error that element is not declared, even it was declared as complex type in XSD. using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Xml.Serialization; using System.IO; namespace Serialization { [Serializable] //use Serializable for serializing a class public class Employee { public string Empno; public string EmpName; public long Salary; public Employee() { Empno = String.Empty; EmpName = String.Empty; Salary = 0; } public Employee(string empno, string ename, long sal) { Empno = empno; EmpName = ename; Salary = sal; } } class Program { static void { Employee emp=new Employee("1234","Scott",25000); //Serialization process XmlSerializer xmlObj = new XmlSerializer(emp.GetType(),"www.employee.com"); String XmlizedString = null; MemoryStream memoryStream = new MemoryStream(); XmlTextWriter XmlObjWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); XmlObjWriter.Formatting = Formatting.Indented; xmlObj.Serialize(XmlObjWriter, emp); memoryStream = (MemoryStream)XmlObjWriter.BaseStream; UTF8Encoding encoding = new UTF8Encoding(); XmlizedString = encoding.GetString(memoryStream.ToArray()); XmlObjWriter.Close(); XmlizedString = XmlizedString.Substring(1); //storing into File FileStream fs = new FileStream("d:\\Emp.xml", FileMode.OpenOrCreate,FileAccess.Write); StreamWriter w = new StreamWriter(fs); w.WriteLine(XmlizedString); w.Flush(); fs.Close(); Console.WriteLine(XmlizedString); Console.ReadLine(); //deserialization Employee e = new Employee(); XmlSerializer xmlDeserialize = new XmlSerializer(e.GetType(),"www.employee.com"); FileStream fr=new FileStream("d:\\Emp.xml", FileMode.Open,FileAccess.Read); e = (Employee) xmlDeserialize.Deserialize(fr); fr.Close(); Console.WriteLine(e.Empno + " : " + e.EmpName + ":" + e.Salary); Console.ReadLine(); } } } Useful Links :- http://www.4guysfromrolla.com/webtech/012302-1.shtml http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=236 http://msdn2.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.xmlserializer.aspx
|
|||||||||||||||||||||||||||||||||||