Sunday, April 20, 2008

How-to get the XML representacion of a DSL Model Element

Today I had to find out how to get the XML representacion of a DSL Model Element. Here you have an extension method for Model Elements (mels) that gets the concrete serializer using the Domain XML Serializer Directory and the Domain Class Id of the target Model Element (mel).

        public static string GetXML(this ModelElement mel)
StringBuilder xml = new StringBuilder();

DomainXmlSerializerDirectory directory = new DomainXmlSerializerDirectory();
directory.AddBehavior(<#Yours DSL Serialization Behavior goes here #>.Instance);
// Gets the serializer of the Mel
            DomainClassXmlSerializer serializer = directory.GetSerializer(mel.GetDomainClass().Id);

if (serializer != null)
using (XmlWriter writer = XmlWriter.Create(new StringWriter(xml)))
serializer.Write(new SerializationContext(directory), mel, writer);
Trace.TraceWarning(Resources.UnableToGetSerializer, mel.GetType().Name);

return xml.ToString();

This page is powered by Blogger. Isn't yours?