is it possible to use C# XmlSerialization API to store single class in two different ways ?
For example
class Test
{
int group1_attr1;
int group1_attr2;
int group2_attr1;
}
I would like to have a way how to split class fields into two parts(groups – with specified attributes) and each time I call Serialize to control which part will be stored. For example if saving as group1
<?xml version="1.0" encoding="utf-8"?>
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org /2001/XMLSchema">
<group1_attr1>0</group1_attr1>
<group1_attr2>0</group1_attr2>
</Test>
if saving as group2
<?xml version="1.0" encoding="utf-8"?>
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org /2001/XMLSchema">
<group2_attr1>0</group2_attr1>
</Test>
Is there a way how to do it in a “clean” way ? If not in xmlserialization then in binary perhaps ?
Then I would like to know what is the best way how to merge those two files into single instance of Test. (Note that fields from group1 and group2 do not overlap)
Here’s code demonstrating how to serialize like you want, however, deserialization will be more tricky because it’s not straightforward to deserialize into an existing instance (see How to use XmlSerializer to deserialize into an existing instance?).
The deserialization could maybe merge the XML before deserializing: