views:

835

answers:

1

I have a class that I want to have opportunities to serialize/deserialize.
It implements interface IXMLConvertable:

public interface IXMLConvertable<T>
where T: new() {
    T deserialize(XElement element);
    void serialize(XElement element);
}

when T is a type of object to deserialize. The question is whether it`s a good practice or not to specify XML tag names not in code, but in string constants, like this:

public class XMLTagger {
    Dictionary<String, String> xmltags;  /*key is fieldname to serialize, value is the tag for it*/
    //... 
    public void addNewTag(String field, String tagForIt) {
        xmltags.Add(field, tagForIt);
    }
    //...
}

I hope you get the idea. This class can be used by every my class which objects I want to serialize/deserialize and provides easy way to get tag you want by the name of the field. Is is a good idea or not?

+3  A: 

Can I ask why you are introducing an extra interface? IXmlSerializable seems pretty similar (albeit XmlWriter/XmlReader oriented). I'm also not sure why deserialize would return something; shouldn't we be deserializing into the current object? (else it is an IXmlConverter<T>, if you see what I mean).

Re the tags... the question is unclear; you don't show any tag names in either code or string constants...

But it is a lot easier to just use XmlSerializer and let it worry about everything...

[XmlType("foo")]
public class Foo {
    [XmlAttribute("bar")]
    public string Bar {get;set;}
    [XmlElement("baz")]
    public int Baz {get;set;}
}
Marc Gravell
Precisely. I suspect the OP wasn't aware of the functionality built into the BCL, so this is good advice.
Noldorin
What is BCL, by the way?
chester89
Base Class Library - i.e. the classes that are supplied in the .NET framework
Marc Gravell
I`ll be working with LINQ and I didn`t plan to use XMLWriter and XMLReader
chester89
If you use XmlSerializer you don't have to use XmlReader/XmlWriter directly - that is largely the point. Re the question; you could perhaps use the same attributes to underpin your own custom serializer?
Marc Gravell