JScripts and XML

 

One of the things that I have been casually thinking about over the last several months is XML and Jscript, especially in the context of WebServices.

JScripts and writing our the likes of XML is just an undertaking that is tedious and time consuming, especially when you compare it to programming languages such as C#.

For those of you that are familiar with the .Net framework and have mucked around with parsing XML you’ve probably come across the System.XML.Serialization assembly. It is a very handy way to allow you to convert the properties of an object to XML and then be able to read that XML in to an object.

This means with larger projects you don’t need to write a heap of custom code to read and write the data, you can just create some objects and then dump them in a single command. It will even handle the nesting of objects and their properties, so you can have a list of values and it will parse out the collect.

This was rather challenging trying to figure out how to use the attributes of the XmlSerializer to control the output. The attributes allow you to control the names of the elements (they default to the property name) and if a property is included or ignored. For examples of the attributes you can use your favourite search engine (https://www.google.co.nz/search?q=xmlserializer+attributes)

We will populate the object with some data, create a TextWriter class, serialise our class writing it out to a file. Then we shall read the file back in to illustrate deserialising the xml file before we output some of the retrieved data.

Things of note in our object it has XMLClass which has a couple of properties.

    public class XMLClass
    {
        public var Data : String;
        public XmlElement(ElementName="Test") var Data2 : String;

        public XmlElement("List") var ListData : System.Collections.ArrayList;
    }

Data property will create an element called “Data” in our output.
Data2 will be renamed to “Test” in our output through using this statement: XmlElement(ElementName=”Test”)
ListData will be renamed “List” and will have the contents

Anyways, enough jibber-jabber, code and xml below – code is commented, if in doubt experiment 🙂 Make small changes. Take careful note that the default output path is to D: drive.

import System;
import System.Windows;
import System.Windows.Controls;
import MForms;

import System.Xml;
import System.Xml.Serialization;
import System.Xml.Serialization.XmlArrayAttribute;
import System.IO;

package MForms.JScript 
{
    class XMLTests
    {
    	// we are going to write our test out to D:\XMLTest.xml
        var gstrPath : String = "d:\\XMLTest.xml";
        
        public function Init(element: Object, args: Object, controller : Object, debug : Object)
        {
        	// 
            var xmcWriteClass : XMLClass = new XMLClass();
            // populate the string with "Hello World"
            xmcWriteClass.Data = "Hello World!";
            // populate the second string
            xmcWriteClass.Data2 = "This is a new beginning";
            // this is a collection of objects - to see how this looks in XML
            xmcWriteClass.ListData = new System.Collections.ArrayList();
            
            var xecExample : XMLExampleClass2 = new XMLExampleClass2();
            // populate the collection objects first object with some data
            xecExample.ClassData2 = "Some Class Data";

			// add the object to the collection
            xmcWriteClass.ListData.Add(xecExample);

			// here we need to define the types of objects
			// so the serialiser doesn't throw an exception
			// XMLClass is defined against the serialiser directly
            var tp : Type[] = new Type[1];
            // typeof doesn't seem to work, so I create an object of the
            // class we want to add and then do a GetType()
            tp[0] = (new XMLExampleClass2).GetType();
            
            // create a streamwriter to write out our data
            var twWriter : TextWriter = new StreamWriter(gstrPath);
            
            // create the XmlSerializer - this will take our object and convert it
            // in to XML.  We get the type of our main class and add the types of any
            // other classes
            var xmsSerial : XmlSerializer = new XmlSerializer(xmcWriteClass.GetType(), tp);

			// Serialise to XML to the text writer
            xmsSerial.Serialize(twWriter, xmcWriteClass);
            
            // close the writer
            twWriter.Close();

			// now lets read the file, create a reader
            var trReader : TextReader = new StreamReader(gstrPath);

			// deserialize the xml from the reader in to an object
            var xmcReadClass : XMLClass = xmsSerial.Deserialize(trReader);

			// close the reader
            trReader.Close();

			// output some of the data that we read
            debug.WriteLine("What we read from the file: " + xmcReadClass.Data + " & " + xmcReadClass.Data2);

        }
    }

    public class XMLClass
    {
        public var Data : String;
        public XmlElement(ElementName="Test") var Data2 : String;

        public XmlElement("List") var ListData : System.Collections.ArrayList;
    }
    
    
    public class XMLExampleClass2
    {
    	public XmlElement(ElementName="TestX") var ClassData2 : String;
    }
}

XML Output

<?xml version="1.0" encoding="utf-8"?>
<XMLClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Data>Hello World!</Data>
  <Test>This is a new beginning</Test>
  <List xsi:type="XMLExampleClass2">
    <TestX>Some Class Data</TestX>
  </List>
</XMLClass>

 

Enjoy!

This entry was posted in Development, M3 / MoveX. Bookmark the permalink.

2 Responses to JScripts and XML

  1. Hi Scott. Thanks for the example. I have some more examples in this post as well: http://thibaudatwork.wordpress.com/2011/09/08/create-xml-in-a-script/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s