Serialize an object with its attribute in xml

Exact duplicate: Is there a way to make an object (with its attributes) serialize to xml?

Ironically enough, this is a duplicate of the previous poster question.


I want to create an object, it contains some attributes of the Validate block such as: [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 these attributes in xml? thank

+1


source to share


2 answers


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();

      



In my experience the serialisaion errors are clear enough, if you are deserializing too and want to deal with the error, the XmlSerializer class has several custom events to connect.

+1


source


You want to serialize your class to XML. It's not going to serialize a single attribute or element.



Use this class to get the job done, but use it with a grain of salt. Sometimes it is difficult to troubleshoot errors that occur when deserializing objects. They might be important users who are expected to change XML files (config, etc.) and not do it correctly.

0


source







All Articles