Nick Udell Nick Udell - 3 months ago 14
C# Question

Serializing references to other serialized objects

I have two serializable Classes:

[Serializable]
public class Word
{
public List<string> similes;
}


.

[Serializable]
public class Lexicon
{
public List<Word> words;
}


both classes are stored as XML files separately, however the XML files for Lexicon comes out like this:

<Word>
<Similes>
<string>Hello</string>
<string>Hi</string>
</Similes>
</Word>

<Word>
<Similes>
<string>Goodbye</string>
<string>Bye</string>
</Similes>
</Word>

<Lexicon>
<Words>
<Word>
<Similes>
<string>Hello</string>
<string>Hi</string>
</Similes>
</Word>
<Word>
<Similes>
<string>Goodbye</string>
<string>Bye</string>
</Similes>
</Word>
</Words>
</Lexicon>


And that's just with two words! You can see how this would quickly get out of hand as more Words were added, additionally the "Hello, Hi" Word, when deserialized, is a different object to the one stored inside the deserialized Lexicon - when they should reference the same object.

So essentially is there a way to make the serialized Lexicon file reference the files produced by serializing the Word instances instead of duplicating the xml?

Answer

You could add a wordID to your serializable Word and reference this ID it in your Lexicon class

[Serializable]
public class Word
{
    public string WordID;
    public List<string> similes;
}

Your Word Class..

<Word>
    <WordID>1</WordID>
    <Similes>
        <string>Hello</string>
        <string>Hi</string>
    </Similes>
</Word>

Lexicon class

public class Lexicon
{
    public List<string> wordIDs;
}

Lexicon could be like

<Lexicon>
    <WordIDs>
        <string>1</string>
        <string>2</string>            
    </WordIDs>
</Lexicon>