1

I have this class:

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

then, this one:

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

finally I have this function;

    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();
        }
    } 

now, let's serialize first one:

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

xml is <SIT_ENTRY STR_ENTRY_ID="Entry1" /> that is exactly what i want. Now, let's serialize second one:

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

xml is

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

and not

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

as I would like. How can I do? Thanks!!!

4

2 回答 2

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);
}
于 2013-07-02T19:43:43.297 回答
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>

如我所愿!

于 2013-07-04T08:02:19.613 回答