2009-10-29 6 views
14

Ho una classe semplice che sto serializzando.Come aggiungere un attributo XML utilizzando DataContract

[DataContract(Name = "Test", Namespace = "")] 
public class Test 
{ 
    [DataMember(Order = 0, Name = "Text")] 
    public string Text { get; set; } 

    public Test() {} 
} 

Questa calcia fuori il seguente codice XML:

<Test> 
    <Text>Text here</Text> 
</Test> 

Quello che voglio è:

<Test> 
    <Text type="MyType">Text here</Text> 
</Test> 

Come posso aggiungere attributi gli elementi XML?

Grazie in anticipo.

risposta

13

Non è possibile aggiungere attributi a un DataContract. Devi utilizzare una classe che implementa ISerializable o utilizzare .Net XmlSerializer.

+0

'IXmlSerializable' per xml. –

+4

A seconda del sistema che esegue la serializzazione, è possibile fare ciò che l'OP sta chiedendo: consultare: http://stackoverflow.com/questions/4858798/datacontract-xml-serialization-and-xml-attributes/4859084#4859084 – jeffreypriebe

0

Non esattamente una risposta, ma puoi provare a implementare IXmlSerializable per controllare completamente il formato di output in formato xml.

0

Sono riuscito a ottenere ciò dichiarando un XElement che ha attributi definiti in esso. Es:

public XElement Text { get; set;} 
+2

Il codice '[DataMember (Name =" test ")] test XElement pubblico = nuovo XElement (" Root ", nuovo Elenco () {" 1 "," 2 "," 3 "});' rese ' 123 ' che probabilmente non è quello che il quenstioner ha inteso – codingdave

-2

Aggiungere l'attributo type con [XMLAttribute] e il valore dell'elemento con [XmlText].

public class Test 
{ 
    public text Text; 

    public Test() 
    { 
     Text = new text(); 
    } 

    [DataContract(Name = "Test", Namespace = "")] 
    public class text 
    { 
     [XmlText] 
     public string Text { get; set; } 
     [XmlAttribute] 
     public string type { get; set; } 
    } 
} 
+1

ho provato e non ho avuto né Testo digito serializzato – codingdave