473,760 Members | 10,633 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

XML Serialization Help

Hello,
I have an existing set of C# classes that encapsulate our application data.
They are in a heirachy with each subclass defining more specific types of
data. I would like to serialize these data objects as XML but perserve the
relationships in the XML document. For example, if my classes were:

public class GenericItem
{
}

public class MoreSpecific : GenericItem
{
}

public class VerySpecific : MoreSpecific
{
}

I would like the XML document to look like,
<GenericItem>
<MoreSpecific >
<VerySpecific ></VerySpecific>
</MoreSpecific>
</GenericItem>

Does anyone know which XML Attributes I should apply to my class properties
so these relationships are maintained? Is this even the best approach? Any
advice or suggestions are greatly appreciated.

Thanks,
Jeff
Nov 12 '05 #1
4 3133
"Jeff T." <Je***@discussi ons.microsoft.c om> wrote in message news:7F******** *************** ***********@mic rosoft.com...
I would like to serialize these data objects as XML but perserve the [inheritance] relationships in the XML document. : : Does anyone know which XML Attributes I should apply to my class properties
so these relationships are maintained? Is this even the best approach?


If you require this degree of customization over the serialized
representation of your objects, then you'll need to implement
IXmlSerializabl e.

Here is an example. I add a piece of data, the 'Word' property,
to the VerySpecific subclass so there's something tangible to
serialize. I also arbitrarily chose to serialize that property as an
attribute. As you'll see, the representation is highly flexible when
using IXmlSerializabl e.

- - - Inheritance.cs
using System;
using System.IO;
using System.Xml;
using System.Xml.Sche ma;
using System.Xml.Seri alization;

public class GenericItem
{
// Default constructors are required to be deserializable.
public GenericItem( ) { }
}

public class MoreSpecific : GenericItem
{
public MoreSpecific( ) { }
}

[XmlRoot("Generi cItem")]
public class VerySpecific : MoreSpecific, IXmlSerializabl e
{

public VerySpecific( ) { }

private string _word = String.Empty;
public string Word { get { return _word; } set { _word = value; } }

// What follows is the IXmlSerializabl e implementation.

public XmlSchema GetSchema( ) { return null; }

public void WriteXml( XmlWriter writer)
{
// writer.WriteSta rtElement( "GenericIte m");
writer.WriteSta rtElement( "MoreSpecific") ;
writer.WriteSta rtElement( "VerySpecific") ;
writer.WriteAtt ributeString( "Word", _word);
writer.WriteFul lEndElement( );
writer.WriteFul lEndElement( );
// writer.WriteFul lEndElement( );
}

public void ReadXml( XmlReader reader)
{
// Highly simplified XmlReader takes advantage of the fact I have only one attribute.
while ( reader.Read( ) )
if ( reader.HasAttri butes )
_word = reader[0];
}
}

public class TestApp
{
public static void Main( )
{
XmlSerializer xs = new XmlSerializer( typeof( VerySpecific));
#if SERIALIZE
VerySpecific vs = new VerySpecific( );
vs.Word = "Is Born";
FileStream fs = new FileStream( "specific.x ml", FileMode.Create New);
xs.Serialize( fs, vs);
fs.Flush( );
fs.Close( );
#else // DESERIALIZE
FileStream fs = new FileStream( "specific.x ml", FileMode.Open);
VerySpecific vs = (VerySpecific) xs.Deserialize( fs);
fs.Close( );
Console.WriteLi ne( "Word {0}", vs.Word);
#endif
}
}
- - -

When you define 'SERIALIZE' in your C# project settings (or via the csc
command-line with the -D option) and build this test application, it'll produce
a serialization of a VerifySpecific object like the following:

- - - specific.xml
<?xml version="1.0" encoding="utf-8"?>
<GenericItem>
<MoreSpecific >
<VerySpecific Word="Is Born"></VerySpecific>
</MoreSpecific>
</GenericItem>
- - -

It does this in two steps. First, the XmlSerializer will put all of the XML produced
by your IXmlSerializabl e implementation' s WriteXml( ) into an element named after
the class being serialized. We have a problem -- the class being serialized is named
VerySpecific. How do we avoid generating?

- - - specifiedTooMuc h.xml
<?xml version="1.0" encoding="utf-8"?>
<VerySpecific >
<GenericItem>
<MoreSpecific >
<VerySpecific Word="Is Born"></VerySpecific>
</MoreSpecific>
</GenericItem>
</VerySpecific>
- - -

We can trick the XmlSerializer into putting the XML content into an outer element
named GenericItem if we use an XmlRootAttribut e on the VerySpecific class.
Having done so, it's no longer necessary for our WriteXml( ) implementation to
write out GenericItem elements, so that's why those have been commented out.

Also note that the XmlWriter you receive in WriteXml( ) is already writing an
XML serialization; so it's not necessary to call WriteStartDocum ent( ) [and of
course, WriteEndDocumen t( )]. In fact, you'll get an error if you try to.

That covers serialization; now on to deserialization . The XmlReader use shown
in ReadXml( ) is very simple since there's only one property here; you may need
to craft your XmlReader code with greater care depending on the characteristics
of your desired serialization format.

Build the Inheritance.cs file without defining SERIALIZATION and it'll operate
in de-serialization mode, reading the specific.xml file it has just written and printing
the very hip message,

Word Is Born

It does this by handing an XmlReader to your implementation of ReadXml( ).
This method is responsible for retrieving any information in the XML serialization
format and mapping that information into your object's properties.

For serialization and deserialization with XmlSerializer, there is no need to
supply an XmlSchema. The XmlSerializer doesn't perform schema-validation
on the XML when it's deserializing it.

In summary, when you need total control over the representation of the
XML when serializing/deserializing, you can fallback to IXmlSerializabl e,
and implementing these well-known serialization and deserialization methods
that operate on XmlWriters and XmlReaders, respectively.
Derek Harmon
Nov 12 '05 #2
Derek,
Thanks for the very helpful reply. A few follow-up questions.....

- Since the IXmlSerializabl e interface is not even documented by
Microsoft, I wonder if this is the best approach. Perhaps I should
rewrite my data classes so they can be automatically serialized? Will
the tradeoffs of doing this be better in the long run?

- If I were to rewrite my data classes, I assume I would need to use a
containership model instead of an inheritance model. In other words,
the classes would have a "HAS A" instead of an "IS A" relationship. The
XML Serialization model does not apply well to Object Oriented
Programming, does it?

- You mentioned that a schema would not need to be supplied. What if I
was to supply a schema? I want the receivers of my data to know how to
read it, as there is no guarantee that my same data classes will be
used on the receiving end. Can a schema be generated automatically or
do I have to define one manually?

Thanks again,
Jeff

Nov 12 '05 #3
"Jeff T." <yo****@comcast .net> wrote in message news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
- Since the IXmlSerializabl e interface is not even documented by
Microsoft, I wonder if this is the best approach. Perhaps I should
rewrite my data classes so they can be automatically serialized? Will
the tradeoffs of doing this be better in the long run?
IXmlSerializabl e was somewhat more documented in .NET 2.0;
so it's still there, for what that's worth. Generally you're right that its
best to avoid types that are undocumented. In this particular case,
it is being used to solve the problem of (de)serializing of XML using
XmlSerializer in whatever format an application requires so in a de
facto way there would probably be reticence to take IXmlSerializabl e
away in future releases. That's not to say the interface might not be
changed if the process of XML (de)serializati on needed some new
step that the interface doesn't presently define, albeit unlikely.

Let's look at implementing a (de)serializati on API yourself. What
methods would it have? A WriteXml method, that writes to the abstract
XmlWriter class? A ReadXml method, that reads from an abstract
XmlReader class? Well, if that's what you're going to implement anyway,
ironically it already exists on IXmlSerializabl e. :-)

The only difference is without marking the class as implementing the
IXmlSerializabl e interface, you must call these methods yourself. If
you implement IXmlSerializabl e, the XmlSerializer will call them for
you.
- If I were to rewrite my data classes, I assume I would need to use a
containership model instead of an inheritance model. In other words,
the classes would have a "HAS A" instead of an "IS A" relationship. The
XML Serialization model does not apply well to Object Oriented
Programming, does it?
XML is all about containment, so it's natural a serialization in XML
has a less than optimal representation for inheritance compared to
a containment model (or that inheritance must be represented by
containment).

I have seen the XML schema you've shown used to represent
inheritance in the past, though. It's not disimilar to the approach
of binary serialization.
- You mentioned that a schema would not need to be supplied.
What if I was to supply a schema?
XmlSerializer won't use it for anything.

The .NET 2.0 Beta 1 documentation states that the XmlSchema is
needed only for generating WSDL proxies, and that it's not called
for serialization/deserialization of instances because XmlSerializer
doesn't schema-validate (which is just as well, because it'd incur
considerable overhead to do so).
I want the receivers of my data to know how to
read it,
You can send them an XML schema document out-of-band, for
example you can implement WriteXml( ) to serialize an xsi:schema-
Location attribute. It's up to the consumer to retrieve it if they need
it.

How much it truly helps the consumers know how to read your
XML instance depends on whether the consuming application is
intelligent enough to use it to generate and execute dynamic code.
Most XML consumers aren't built that well, though, or at least
few of us are fortunate enough to have them be commonplace.
as there is no guarantee that my same data classes will be
used on the receiving end. Can a schema be generated
automatically or do I have to define one manually?


There's an XML Schema Inference tool here,

http://apps.gotdotnet.com/xmltools/xsdinference/

Several popular XML editors also include it as a
feature. The better implementations allow you to
specify heuristics to improve the inference.

At least, you can pass xsd.exe a file with an .xml
extension and it'll infer a schema document.

After one of these programs guesses one of the millions of
possible schemas that will validate your instance document,
it's wise to revise it manually. :-)
Derek Harmon
Nov 12 '05 #4
Once again you have been very helpful. Thank you.

Jeff

Nov 12 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
3175
by: Aaron Clamage | last post by:
Hi, I'm not sure that if this is the right forum, but any help would be greatly appreciated. I am porting some java serialization code to c# and I can't figure out the correct way to do it. It seems that either I can use default serialization or implement ISerializable. Is there any way to do both (e.g. extend the default serialization). In other words, I want to be able to implement my custom serialization code but call the...
2
6652
by: Dave Veeneman | last post by:
I'm working on a project where I have to persist data to a file, rather than to a database. Basically, I need to save the state of several classes, each of which will have a couple of dozen instances. I have set it up to use binary serialization to a single file, which works well. However, I have learned that changes to my classes break the old serialized files. While my object model is pretty stable, I am concerned that using binary...
5
2826
by: francois | last post by:
First of all I would to to apologize for resending this post again but I feel like my last post as been spoiled Here I go for my problem: Hi, I have a webservice that I am using and I would like it to return an XML serialized version of an object.
6
2717
by: Uttam | last post by:
Hello, We are at a very crucial decision making stage to select between .Net and Java. Our requirement is to download a class at runtime on the client computer and execute it using remoting or rmi. Just to keep my question short I am posting trimmed version of my code. //file: Serializable.cs
4
1806
by: mdb | last post by:
I have a class (very simple int type data, as shown below) that I have serialized to disk. In my next version of the program, I have added some variables to that class. I'm expecting that this will break the serialization when I try to load the object from disk. I know there is something in .NET 2.0 to handle this, but how can I do it with .NET 1.1? Some sample code would be much appreciated... // The old version class Data
4
7486
by: Brian Keating | last post by:
wonder if anyone can help me here, i've a framework 1.1 dataset which i serialize in framework 1.1 and deserialize in framework 2.0. This is fine, problem is that i want to modify some of the records in framework 2.0 and serialize the data so framework 1.1 can deserialize it and do what it required. Is this possible?
0
1203
by: nobin01 | last post by:
Dear sir; I want ur Help in serialization.I know serialization.I Know binary,soap and xmlserialization also.But i want ur help in following topics.pls help me as soon as possible.I have search in site but only basics serialization is there. Topics: 1) serialize a nested object in mutiple files by maintaining the relation on parent level. ie, let say object1 containts object2 and object2 contains object3 , while serializing the object1,...
8
12567
by: =?Utf-8?B?UGlnZ3k=?= | last post by:
Hi to all, I am getting this System.OutOfMemoryException calling the Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(<stream>,<Obj>) method. The type of <streamis IO.MemoryStream =====Exception: System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
2
5565
by: mkvenkit.vc | last post by:
Hello, I hope this is the right place to post a question on Boost. If not, please let me know where I can post this message and I will do so. I am having a strange problem with std::string as I am trying to read from a binary archive using Boost serialization. I am new to this, and it is possible that I have not understood the usage. In the code below, the string "faultblock" seems to be causing the problem. The code crashes in the ia...
0
9521
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10107
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9945
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9900
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9765
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8768
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5214
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5361
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3863
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.