2010-03-10 2 views
0

J'ai une classe avec une propriété dedans. Je veux savoir si nous pouvons définir l'attribut tel que XmlAttributeAttribute.AttributeName.Définir Attribut @ temps d'exécution

Ici, l'attribut ElementName est défini au moment de la compilation, je veux savoir si nous pouvons définir @ run time.

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

Votre question est un peu floue, pouvez-vous essayer de la reformuler? – Kane

+0

@Lasse V. Karlsen Merci pour le formatage :) – Ravisha

Répondre

4

Vous recherchez 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); 
    //... 
+0

C'est ce que je cherchais. Merci mon pote – Ravisha

0

Vous devrez implémenter l'interface ISerializable et passer outre les fonctions suivantes dans lesquelles vous pouvez définir des attributs au moment de l'exécution (d'une liste ou d'une autre façon, vous voudrez peut-être)

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

un coup d'oeil à CodeProject

+0

Vous voulez probablement dire IXmlSerializable - http://msdn.microsoft.com/fr-fr/library/system.xml.serialization.ixmlserializable.aspx –

Questions connexes