views:

336

answers:

3

Exact Duplicate of: http://stackoverflow.com/questions/390800/is-there-a-way-to-do-object-with-its-attributes-serializing-to-xml

Quite Ironically, it's a duplicate of the poster's previous question.


I want create an object, it contains some Validate application block attributes like: [Serializable] public class FormElement:IValidated {

    [StringLengthValidator(1, 50, MessageTemplate = "The Name must be between 1 and 50 characters")]
    public String username
    {
        get;
        set; 
    }

    [RangeValidator(2007,RangeBoundaryType.Inclusive,6000,RangeBoundaryType.Inclusive,MessageTemplate="input should be in 2007 to 6000")]
    public int sequencenumber
    {
        get;
        set;
    }

    [RegexValidator(@"^\d*\.{0,1}\d+$", MessageTemplate = "input value can not be empty or negative")]
    public string medicalvalue
    {
        get;
        set;
    }

}

how do I serialize those attributes to xml? thanks

A: 

serialize whole objct to xml document

edit your post. This is not a forum thread.
StingyJack
I agree that more details in this answer would have been more useful....
Yossi Dahan
A: 

You want to serialize your Class to XML. Its not going to serialize an individual attribute or element.

Use this class to do the work you need, but use it with a grain of salt. It is sometimes difficult to troubleshoot errors that occur when deserializing the objects. This can be important users are expected to alter the XML files (config's, etc) and dont do it correctly.

StingyJack
+1  A: 

Use the XmlSerializer class:

//Create serializer instance, passing in the type of the class 
XmlSerializer serializer = 
  new XmlSerializer(typeof(FormElement));
// Create a FileStream to write with (could be any other stream)
Stream writer = new FileStream(filename, FileMode.Create);
// Serialize the object, and close the TextWriter
 serializer.Serialize(writer, i);
writer.Close();

From my experience serialisaion errors are fairly clear, if you're deserialising as well and wish to handle error the XmlSerializer class has a few userful events to hook up to.

Yossi Dahan