我有此類:序列化的對象是在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>
如我所願。我能怎麼做?謝謝!!!