我正在尝试使用XmlSerializer将对象序列化为XML
我希望得到这样的东西:
<user>
<username>administrator</username>
<email>administrator@email.com</email>
<roles>
<roleId>D3DCBCDA-AD61-4764-B5A1-057D654F1C26</roleId>
<role>admin</role>
<roleId>D4DCBCDA-AD61-4764-B5A1-057D654F1C26</roleId>
<role>editor</role>
</roles>
</user>
内部异常
无法序列化类型&{39; System.Collections.Generic.IList`1 [[Model.DTO.RoleDTO,Domain.Model,Version = 1.0.0.0,Culture = neutral,PublicKeyToken =]的成员
'Model.DTO.UserDTO.role'
null]]&#39;,有关详细信息,请参阅内部异常。
栈跟踪
at System.Xml.Serialization.StructModel.CheckSupportedMember(TypeDesc typeDesc, MemberInfo member, Type type)
at System.Xml.Serialization.StructModel.GetPropertyModel(PropertyInfo propertyInfo)
at System.Xml.Serialization.StructModel.GetFieldModel(MemberInfo memberInfo)
at System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter)
at System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a, RecursionLimiter limiter)
at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)
代码
IList<RoleDTO> rl = new List<RoleDTO>();
rl.Add(new RoleDTO { roleId = new Guid("D3DCBCDA-AD61-4764-B5A1-057D654F1C26"),
role = "admin" });
rl.Add(new RoleDTO { roleId = new Guid("D4DCBCDA-AD61-4764-B5A1-057D654F1C26"),
role = "editor" });
UserDTO user = new UserDTO
{
username = "administrator",
email = "administrator@email.com",
role = rl
};
XmlSerializer x = new System.Xml.Serialization.XmlSerializer(xml.GetType());
XmlSerializer xsSubmit = new XmlSerializer(typeof(FisaxmlDTO));
StringWriter sww = new StringWriter();
XmlWriter writer = XmlWriter.Create(sww);
xsSubmit.Serialize(writer, user);
var xmll = sww.ToString(); // Your xml
型号:
namespace Model.DTO
{
public class UserDTO
{
public string username { get; set; }
public string email { get; set; }
public IList<RoleDTO> role { get; set; }
}
public class RoleDTO
{
public Guid roleId { get; set; }
public string role { get; set; }
}