问题是我没有得到我想要的XML结构。我的守则如下:
[DataContract]
public class Persons
{
[DataMember]
public List<Person> Personas;
}
[DataContract]
public class Person
{
[DataMember(Name="SSN")]
public long SSN
{
get;
set;
}
[DataMember(Name="Name")]
public string Name
{
get;
set;
}
当我运行DataContractSerializer时,它返回的XML是:
<Persons xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WCFTest">
<Personas>
<Person>
<Name>B</Name>
<SSN>1234</SSN>
</Person>
<Person>
<Name>I</Name>
<SSN>5678</SSN>
</Person>
</Personas>
</Persons>
我想删除元素Persons或Personas,root元素应该包含Person列表。
答案 0 :(得分:2)
如果您希望根元素是Person列表,只需序列化List而不是序列化Personas。
DataContractSerializer ser =
new DataContractSerializer(typeof(List<Person>))
ser.WriteObject(writer, persons.Personas)
而不是
DataContractSerializer ser =
new DataContractSerializer(typeof(Persons))
ser.WriteObject(writer, persons)
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx