Possible from serialization?

  • Thread starter Thread starter TJ
  • Start date Start date
T

TJ

Hi,

..NET framework 2.0

[Serializable]
public class Test
{
public Test()
{
}


private Data[] data;
[XmlElement("Data")]
public Data[] Data
{
get
{
return this.data;
}
set
{
this.data = value;
}
}
}

[Serializable]
public class Data
{
public Data()
{
}
private int number = 0;
[XmlAttribute("Number")]
public int Number
{
get
{
return this.number;
}
set
{
this.number = value;
}
}
}

Test t = new Test();
Data d1 = new Data();
d1.Number = 1;
Data d2 = new Data();
d2.Number = 2;
Data d3 = new Data();
d3.Number = 3;
Data d4 = new Data();
d4.Number = 4;
t.Data = new Data[] { d1, d2, d3, d4 };

t object was serialized through XmlSerializer...
It generates something like this xml..

<Test>
<Data Number="1" />
<Data Number="2" />
<Data Number="3" />
<Data Number="4" />
</Test>

Is there any way I can generate this xml like this....differnet parent-child
relationship for Data element....I menat...
For example...this should be generated something like..

<Test>
<Data Number="1" >
<Data Number="2" />
</Data>
<Data Number="3" />
<Data Number="4" />
</Test>

or

<Test>
<Data Number="1" >
<Data Number="2" />
<Data Number="3" />
</Data>
<Data Number="4" />
</Test>

or

<Test>
<Data Number="1" >
<Data Number="2" />
</Data>
<Data Number="3" >
<Data Number="4" />
</Data>
</Test>

Parent-child relationship for Data element is decided depending on some
logic..
I have the logic, but how do I apply it at the time serialization happens?..
Is this possible by using XmlSerializer?..

I know that I could create the node manually without using
serialization(XmlSerializer)...however,
Would like to check whether there is any way that I can do this with
serialization...

Any idea?

Thanks,
 
Depending on how you've representing the relationship, you may be able to 
simply serialize the data structure where the relationship _is_  
represented, or have your class implement ISerializable and include logic 
within the class to update the representation based on whatever  
information you want.

Note that he is doing XML serialization. This means that ISerializable
is not applicable here, and that [Serializable] attribute in the
original example was meaningless and unneeded.
 
It seems you mean a relationship as below. Change the definition of class
Data to be:

[Serializable]
public class Data
{
public Data()
{
RelatedData = new List<Data>();
}

[XmlElement("Data")]
public List<Data> RelatedData { get; set; }

private int number = 0;
[XmlAttribute("Number")]
public int Number
{
get
{
return this.number;
}
set
{
this.number = value;
}
}
}

Then change the main routine to:

Test t = new Test();
Data d1 = new Data();
d1.Number = 1;
Data d2 = new Data();
d2.Number = 2;
d1.RelatedData.Add(d2);
Data d3 = new Data();
d3.Number = 3;
Data d4 = new Data();
d4.Number = 4;
t.Data = new Data[] { d1, d3, d4 };
 
Back
Top