views:

56

answers:

2

I have a class with a property in it.I want to know if we can set the attribute such as XmlAttributeAttribute.AttributeName.

Here the ElementName attribute is set at compile time,i want top know can we set @ run time.

public class MyTestClass
{
    [XmlElement(ElementName = "MyAttributeName")]
    public int MyAttribute
    {
        get
        {
            return 23;
        }
    }
}
A: 

You will need to implement ISerializable interface and override the following functions in which you can set attributes at run time(from a list or any other way you might want)

public Employee(SerializationInfo info, StreamingContext ctxt)
{
    //Get the values from info and assign them to the appropriate properties

    EmpId = (int)info.GetValue("EmployeeId", typeof(int));
    EmpName = (String)info.GetValue("EmployeeName", typeof(string));
}

//Serialization function.

public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
    //You can use any custom name for your name-value pair. But make sure you

    // read the values with the same name. For ex:- If you write EmpId as "EmployeeId"

    // then you should read the same with "EmployeeId"

    info.AddValue("EmployeeId", EmpId);
    info.AddValue("EmployeeName", EmpName);
}

Have a look at CodeProject

LnDCobra
You probably mean IXmlSerializable - http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx
Lasse V. Karlsen
+3  A: 

You are looking for XmlAttributeOverrides.

  XmlAttributeOverrides attOv = new XmlAttributeOverrides();
  XmlAttributes attrs = new XmlAttributes();
  attrs.XmlElements.Add(new XmlElementAttribute("MyAttributeName"));
  attOv.Add(typeof(MyTestClass), "MyAttribute", attrs);
  XmlSerializer serializer = new XmlSerializer(typeof(MyTestClass), attOv);
  //...
Guillaume
Thats what i was looking for.thanks Buddy
Ravisha