2013-07-02 34 views
1

我有此類:序列化的對象是在C#與XmlSerializer的對象的列表,選擇陣列項標籤

[XmlRoot("SIT_ENTRY")] 
public class SitEntry 
{ 
    [XmlAttribute("STR_ENTRY_ID", DataType = "string")] 
    public string EntryId { get; set; } 
} 

然後,這一個:

[XmlRoot("SIT_ENTRY_LIST")] 
public class SitEntryList : List<SitEntry> 
{ 
} 

終於我有這樣的功能;

public string SerializeToString<T>(T value) 
    { 
     var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }); 
     var serializer = new XmlSerializer(value.GetType()); 
     var settings = new XmlWriterSettings(); 
     settings.Indent = false; 
     settings.OmitXmlDeclaration = true; 
     using (var stream = new StringWriter()) 
     using (var writer = XmlWriter.Create(stream, settings)) 
     { 
      serializer.Serialize(writer, value, emptyNamepsaces); 
      return stream.ToString(); 
     } 
    } 

現在,讓我們序列化第一招:

var sitentry = new SitEntry 
{ 
    EntryId = "Entry1" 
}; 
var sXml = SerializeToString(sitentry); 

XML是<SIT_ENTRY STR_ENTRY_ID="Entry1" />這就是我想要的東西。 現在,讓我們連載第二個:

var sitentrylist = new SitEntryList 
{ 
    new SitEntry 
    { 
     EntryId = "Entry1" 
    }, 
    new SitEntry 
    { 
     EntryId = "Entry2" 
    } 
}; 
sXml = SerializeToString(sitentrylist); 

XML是

<SIT_ENTRY_LIST> 
    <SitEntry STR_ENTRY_ID="Entry1" /> 
    <SitEntry STR_ENTRY_ID="Entry2" /> 
</SIT_ENTRY_LIST> 

,而不是

<SIT_ENTRY_LIST> 
    <SIT_ENTRY STR_ENTRY_ID="Entry1" /> 
    <SIT_ENTRY STR_ENTRY_ID="Entry2" /> 
</SIT_ENTRY_LIST> 

如我所願。我能怎麼做?謝謝!!!

回答

0

我發現,這裏有一個可能的解決方案:

[XmlRoot("SIT_ENTRY_LIST")] 
public class SitEntryList 
{ 
    [XmlElement("SIT_ENTRY", IsNullable = true)] 
    public List<SitEntry> EntryList { get; set; } 
} 

[...] 

var sitentrylist = new SitEntryList 
{ 
    EntryList = new List<SitEntry> 
    { 
     new SitEntry 
     { 
      EntryId = "Entry1" 
     }, 
     new SitEntry 
     { 
      EntryId = "Entry2" 
     } 
    } 
}; 
s = SerializeToString(sitentrylist); 

輸出

<SIT_ENTRY_LIST> 
    <SIT_ENTRY STR_ENTRY_ID="Entry1" /> 
    <SIT_ENTRY STR_ENTRY_ID="Entry2" /> 
</SIT_ENTRY_LIST> 

,因爲我想要的!

0

在老式的XmlSerializer中有一些奇怪的行爲,我從來沒有想過。我從來沒有遇到過類似DataContractSerializer的問題。

有沒有理由不能使用DataContractSerializer? http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx

[DataContract("SIT_ENTRY")] 
public class SitEntry 
{ 
    [DataMember("STR_ENTRY_ID")] 
    public string EntryId { get; set; } 
} 


[DataContract("SIT_ENTRY_LIST")] 
public class SitEntryList : List<SitEntry> 
{ 
} 

using (MemoryStream requestObjectStream = new MemoryStream()) 
{ 
    DataContractSerializer serializer = new DataContractSerializer(typeof(SitEntry)); 
    serializer.WriteObject(requestObjectStream, objectToSerialize); 
}