2010-01-18 11 views
5

Próbuję utworzyć obiekt C# do serializacji/deserializacji za pomocą właściwości string. Nieruchomość musi generować element, a także mieć atrybut:C# Element łańcucha XML z atrybutem Nazwa

np

... 
<Comment Name="CommentName"></Comment> 
... 

Jeśli właściwość jest ciągiem, nie mogę zobaczyć, jak dodać atrybut, a jeśli komentarz jest obiektem z właściwościami Nazwa i Wartość generuje:

... 
<Comment Name="CommentName"> 
    <Value>comment value</Value> 
</Comment> 
... 

Jakieś pomysły?

Odpowiedz

6

Trzeba by odsłonić te 2 nieruchomości od typu i użyć atrybutu [XmlText] aby wskazać, że nie powinny generować dodatkowy element:

using System; 
using System.Xml.Serialization; 
public class Comment 
{ 
    [XmlAttribute] 
    public string Name { get; set; } 
    [XmlText] 
    public string Value { get; set; } 
} 
public class Customer 
{ 
    public int Id { get; set; } 
    public Comment Comment { get; set; } 
} 
static class Program 
{ 
    static void Main() 
    { 
     Customer cust = new Customer { Id = 1234, 
      Comment = new Comment { Name = "abc", Value = "def"}}; 
     new XmlSerializer(cust.GetType()).Serialize(
      Console.Out, cust); 
    } 
} 

Jeśli chcesz spłaszczyć te właściwości na samego obiektu (instancja Customer w moim przykładzie), potrzebny jest dodatkowy kod, aby model obiektu udawał, że pasuje do tego, co chce, lub całkowicie oddzielny model DTO.

Powiązane problemy