How do I serialize a CLSA object to XML?

How do I serialize a CLSA object to XML?

Old forum URL: forums.lhotka.net/forums/t/4442.aspx


SouthSpawn posted on Saturday, March 01, 2008

Can anyone post a function to do this?

Thanks,
Mark

tmg4340 replied on Saturday, March 01, 2008

Well... the short answer is "in general, you don't."

But since that's proably not very helpful... Smile [:)]

This is a rather broad question, and it might help us to know a bit more about what you're trying to accomplish.  But there are a few problems you'll run into, no matter what your reasons for trying:

1. XML serialization doesn't really adhere to the "NonSerialized" attribute, at least not how it's used in CSLA.  That's because XML serialization doesn't care about fields - it only cares about properties.

2. More specifically, XML serialization only cares about read/write properties.  This means that any read-only properties in your BO won't be serialized at all.  And any data you might want in your XML stream that's not referenced by any property also won't be there.

3. XML serialization requires a default public constructor.

Alas, all is not lost.  If you take a look at the "IXmlSerializable" interface, you will see that it allows you to customize the XML serialization and deserialization of your object to include whatever data you want, in whatever format you want.  It can be time-consuming, since you have to implement the interface on every object you want to serialize to XML in your object graph.  But you can get it done.  However, that won't get you around the public-constructor limitation - you're pretty much stuck on that one.  And while that's not a definite no-no for CSLA objects, it is heavily discouraged.

But just because you can do it doesn't mean you should.  Thus, my original question: what are you trying to accomplish?

- Scott

SouthSpawn replied on Sunday, March 02, 2008

Basically, I wanted to save the object as an XML field into the database.
Just in case I need to grab that XML someday and send to another system such as a AS400 system.

RockfordLhotka replied on Sunday, March 02, 2008

In that case, if it were me I'd look at using the XLinq capabilities of .NET 3.5 to implement DataPortal_XYZ methods that create and store/retrieve the XML.

It is true that it is difficult or impossible to use the standard XmlSerializer, and it is unwise to try and use the DataContractSerializer (because you'll get fields you don't want like _isDirty, and you can't surpress that without breaking CSLA).

Besides, what you are describing is data access, pure and simple, and so it is a mapping problem between your data storage mechanism and your object model - which is the purpose of the code in (or called by) the DataPortal_XYZ methods.

SouthSpawn replied on Tuesday, March 04, 2008

Rocky,
 
This is a little new to me.
 
Can you point me to a good online resource that talks about this and shows examples?

Thanks,
Mark

Copyright (c) Marimer LLC