我正在尝试使用XmlSerializer将对象序列化为XML
我希望得到这样的东西:
<User>
<username>administrator</username>
<email>administrator@email.com</email>
<roles>
<whatever id="D3DCBCDA-AD61-4764-B5A1-057D654F1C26">
<role>admin</role>
</whatever>
</roles>
</user>
但相反,我得到了这个:
<User>
<username>administrator</username>
<email>administrator@email.com</email>
<roles>
<RoleDTO id="D3DCBCDA-AD61-4764-B5A1-057D654F1C26">
<role>admin</role>
</RoleDTO>
</roles>
</User>
代码
XmlSerializer x = new System.Xml.Serialization.XmlSerializer(xml.GetType());
XmlSerializer xsSubmit = new XmlSerializer(typeof(UserDTO));
StringWriter sww = new StringWriter();
XmlWriter writer = XmlWriter.Create(sww);
xsSubmit.Serialize(writer, user);
var xmll = sww.ToString(); // My xml
List<RoleDTO> rl = new List<RoleDTO>();
rl.Add(new RoleDTO { roleId = new Guid("D3DCBCDA-AD61-4764-B5A1-057D654F1C26"), role = "admin" });
UserDTO user = new UserDTO
{
username = "administrator",
email = "administrator@email.com",
role = rl
};
模型
namespace Model.DTO
{
[XmlRoot("User")]
public class UserDTO
{
public string username { get; set; }
public string email { get; set; }
public List<RoleDTO> role { get; set; }
}
public class RoleDTO
{
[XmlAttribute("Id")]
public Guid roleId { get; set; }
public string role { get; set; }
}
}
我试图用[XmlRoot("whatever")]
[XmlElement("whatever")]
装饰类RoleDTO而没有成功。
有什么想法吗?
答案 0 :(得分:1)
您需要使用
修饰User DTO类的role属性var string = 'some stuff $14.99';
var pos = string.indexOf('$');
// pos = 11
不是RoleDTO类。
[XmlElement("whatever")]