all groups > dotnet xml > february 2004 >
You're in the

dotnet xml

group:

Xml Serialization - Guid problem...


Xml Serialization - Guid problem... Jiho Han
2/26/2004 7:22:07 PM
dotnet xml:
I generated a class from a schema. One of the fields are typed as
System.Guid. Perfect.
The only problem is when this class serializes, the guid field serializes as
8c4a969b-2aa4-4679-b170-d9f6441f7c6d, when I need it as
{8A3ACA06-A7DE-41A5-B584-063E7CF391BB}, all upper, and with braces.

Is there a way to force the XmlSerializer to serialize as the latter format?

I tried to turn the field into a string property with private field type
Guid. That way, I can store it as a guid but format it the way I want. The
problem this time - the properties serialize last and my elements are now
out of order.

Is there a way to force a certain order in serialization?

I am looking at a few options:

1. turn all fields into properties.

2. write a custom XmlWriter which will replace all guid fields into the
correct format upon serializing.

3. write a custom XmlReader which will replace all guid fields into the
correct format upon deserializing.

4. use xsl transformation.

It seems to me that option #1 is the easiest to implement but that would
mean my class cannot be generated automatically any more.

Any other suggestions?
Thanks much.
Jiho

Re: Xml Serialization - Guid problem... Derek Harmon
2/26/2004 7:55:52 PM
[quoted text, click to view]

Option 5, instead of wrapping the formatting logic within a property,
wrap it within a nested class. Here is an example,

- - - SerializingFormattedGuid.cs
[XmlRoot( ElementName="SerializeFormattedGuidExample")]
public class SerializingFormattedGuid
{
// This is the nested class, containing a property that manages
// the formatting of the GUID.
public class GuidContainer
{
private string mGuid;
public GuidContainer() {
this.mGuid = System.Guid.NewGuid( ).ToString( "B").ToUpper( );
}
public GuidContainer( System.Guid itsGuid) {
this.mGuid = itsGuid.ToString( "B").ToUpper( );
}
[XmlText]
public string Guid
{
get { return mGuid; }
set { mGuid = value; }
}
}

[XmlElement("Uno")]
public int fieldOne;

[XmlElement("Dos")]
public GuidContainer guid;

[XmlElement("Tres")]
public int fieldThree;

public SerializingFormattedGuid( )
{
// Optionally, pass as an argument the specific GUID
// you wish to assign.
//
guid = new GuidContainer( );
fieldOne = 1;
fieldThree = 3;
}
}
- - -

It cries out "hack," of course. What would be nice would be a way to
specify an IFormatProvider, no?


Derek Harmon

Re: Xml Serialization - Guid problem... Jiho Han
2/26/2004 10:55:36 PM
Interesting approach. That still involved editing of the source generated
by xsd so I might as well make them properties.

I can't wait for version 2.0 of the framework... sigh...

[quoted text, click to view]

AddThis Social Bookmark Button