我有这堂课:
[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 :(得分: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);
}
答案 1 :(得分: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>
我想要的!