How to automatically generate XML and object classes from XSD

Source: Internet
Author: User
Tags how to generate xsd from xml validate xml against xsd xsd example

Sometimes XML is used as the data source in the project. Therefore, you need to define the XML file and corresponding classes. The best way is to define XSD first, then automatically generate the entity class, and finally generate XML and fill data; when reading an XML data source, you first use XSD to verify the XML data format, and then automatically read the object class for use.

The process of defining XSD is similar to the process of designing the table structure. The two can also be converted to each other.

This article discusses how to define an XSD file (XML Schema), then automatically generate an object class, and finally generate an XML file, and how to verify the validity of the XML file based on XSD. For your reference during project creation.

1. Add an XSD file in VS2005. For the XSD example, refer:

Http://www.15seconds.com/issue/031209.htm

Http://www.cduce.org/manual_schema_samples.html

 

2. Use the vs2005tool xsd.exe(SDK \ v2.0 \ Bin \ xsd.exe)Automatically generate object classes:

Xsd/c/namespace: myCompany/language: CS temp1.xsd

You can also generate a DataSet class:

Xsd/dataset/language: CS temp1.xsd

(Class files and XSD can be converted to each other, that is, you can also convert them into classes and then generate XSD automatically)

Automatically read XML data to entity classes:

XmlSerializer xs = new XmlSerializer (typeof (myClassType ));
Using (FileStream fs = new FileStream (XmlFilePath, FileMode. Open ))
{
Return (myClassType) xs. Deserialize (fs );
}


3. How to generate XSD from XML?

-You can use a tool, such as XMLSpy. First open XML, then DTD/Schema-> Generate DTD/Schema, and select W3c Sehcma.

-This method may not generate an XSD that exactly meets your needs. You need to modify it.


4. How to generate XML from XSD?

-You can use other tools, such as XMLSpy, DTD/Schema-> Generate sample XML file...

-Classes can be generated by XSD, and code can be written to instantiate the class, and serialized as XML

-How to automatically set a null value for each attribute of the class: (use the reflection method)

Sample Code:

/** // <Summary>
/// Get all properties and set default value
/// </Summary>
/// <Typeparam name = "T"> Type </typeparam>
/// <Param name = "item"> Object </param>
Private static void ReflctProperties <T> (T item)
{
PropertyInfo [] pty = typeof (T). GetProperties ();
Type t = item. GetType ();

If (pty! = Null)
{
Foreach (PropertyInfo info in pty)
{
If (! Info. CanWrite) continue;

If (info. PropertyType = typeof (String ))
{
T. GetProperty (info. Name). SetValue (item, String. Empty, null );
}
If (info. PropertyType = typeof (Boolean ))
{
T. GetProperty (info. Name). SetValue (item, true, null );
}
}
}
}

-Attributes of the reflected read class:
 

Public static object GetProperty <T> (T item, string PropertyName)
{
PropertyInfo propertyInfo = item. GetType (). GetProperty (PropertyName );
If (propertyInfo! = Null)
{
Return propertyInfo. GetValue (item, null );
}
Return null;
}



-How to serialize to XML?

/** // <Summary>
/// Serialize class instance to XML file
/// </Summary>
/// <Typeparam name = "T"> type </typeparam>
/// <Param name = "XMLFileToCreate"> XMLFileToCreate </param>
/// <Param name = "instance"> class instance </param>
Public void Serialize <T> (string XMLFileToCreate, T instance)
{
If (instance = null) return;

XmlSerializer xs = new XmlSerializer (typeof (T ));
Using (StreamWriter sw = new StreamWriter (XMLFileToCreate ))
{
Xs. Serialize (sw, instance );
}
}

 

(Link:Use XMLSerializer class for persistent data)

 

 
5. How to Use XSD to verify the validity of XML files:

-When XMLSpy is used, first Assign XSD and then verify (in fact, it is to set the schema referenced in XML. Note that the schema may reference other Schemas)

-Verification in code:

Validate XML against XSD # region Validate XML against XSD

Public class Validator
{
Private string errMsg;

/** // <Summary>
/// Validation Error Msg
/// </Summary>
Public string validationErrMsg
{
Get {return errMsg ;}
Set {errMsg = value ;}
}


/** // <Summary>
/// Validate XML against schema
/// </Summary>
/// <Param name = "XSD"> </param>
/// <Param name = "XMLFile"> </param>
/// <Param name = "LocationDefined"> </param>
/// <Returns> </returns>
Public bool Validate (string XSD, string XMLFile, bool LocationDefined)
{
Bool isValid = true;

Try
{
Stream schemaFile = null;

XmlReaderSettings settings = new XmlReaderSettings ();
ValidationEventHandler SchemaValidationEventHandler = new ValidationEventHandler (ValidationCallBack );

Settings. ValidationType = ValidationType. Schema;
Settings. ValidationFlags | = XmlSchemaValidationFlags. AllowXmlAttributes;
Settings. ValidationFlags | = XmlSchemaValidationFlags. ReportValidationWarnings;
Settings. ValidationEventHandler + = SchemaValidationEventHandler;

If (LocationDefined = true)
{
Settings. ValidationFlags | = XmlSchemaValidationFlags. ProcessInlineSchema;
Settings. ValidationFlags | = XmlSchemaValidationFlags. ProcessSchemaLocation;
}
Else
{
SchemaFile = new FileStream (XSD, FileMode. Open );

XmlSchema tmsSchema = XmlSchema. Read (schemaFile, SchemaValidationEventHandler );

Settings. Schemas. Add (tmsSchema );
}

Using (XmlReader reader = XmlReader. Create (XMLFile, settings ))
{
String test;

While (reader. Read () & isValid = true)
{
Test = reader. Name;
}
};

If (schemaFile! = Null)
{
SchemaFile. Close ();
}
}
Catch (Exception e)
{
ValidationErrMsg + = "Exception occured when validating." + e. Message;

IsValid = false;
}

Return isValid;
}

/** // <Summary>
/// Display any warnings or errors.
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "args"> </param>
Public void ValidationCallBack (object sender, ValidationEventArgs args)
{
If (args. Severity = XmlSeverityType. Warning)
{
ValidationErrMsg + = "Matching schema not found. No validation occurred." + args. Message;
ValidationErrMsg = args. Message;
}
Else
{
ValidationErrMsg + = "\ nValidation error:" + args. Message;

ValidationErrMsg = args. Message;
}
}
}
# Endregion

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.