[英]In C#, how do I serialize my derived object to this XML?
I am trying to send some XML to a third party, and the format of the element I need to send looks like this: 我正在尝试将一些XML发送给第三方,而我需要发送的元素的格式如下所示:
<CONTACT>
<CONTACTMETHODS>
<PHONE number='202-555-1234' />
<EMAIL address='myname@gmail.com' />
</CONTACTMETHODS>
</CONTACT>
I have the following model in C#, which I am trying to serialize to an XML string: 我在C#中有以下模型,我正在尝试将其序列化为XML字符串:
[XmlRoot("CONTACT")]
[XmlInclude(typeof(Phone))]
[XmlInclude(typeof(Email))]
public class Contact
{
[XmlArray("CONTACTMETHODS")]
public List<ContactMethod> ContactMethods { get; set; }
}
public abstract class ContactMethod
{
}
[XmlRoot("PHONE")]
public class Phone : ContactMethod
{
[XmlAttribute("number")]
public string Number { get; set; }
}
[XmlRoot("EMAIL")]
public class Email : ContactMethod
{
[XmlAttribute("address")]
public string Address { get; set; }
}
The XML that is sent to the string is: 发送到字符串的XML是:
<CONTACT>
<CONTACTMETHODS>
<ContactMethod xsi:type="Phone" number="202-555-1234" />
<ContactMethod xsi:type="Email" address="myname@gmail.com" />
</CONTACTMETHODS>
</CONTACT>
How do I get the serializer to create the XML I need? 如何获得序列化程序来创建所需的XML?
Edit: As requested, here is the code to serialize the object: 编辑:根据要求,以下是序列化对象的代码:
protected string ObjToXmlString<T>(T obj) where T : class
{
var stringwriter = new System.IO.StringWriter();
var serializer = new XmlSerializer(typeof(T));
serializer.Serialize(stringwriter, obj);
var returnXml = stringwriter.ToString();
return returnXml;
}
I was thinking about it in the wrong way. 我以错误的方式思考它。 Instead of an abstract class that Phone and Email derive from, I did this:
我不是通过电话和电子邮件派生的抽象类,而是这样做的:
[XmlRoot("CONTACT")]
[XmlInclude(typeof(CR.Models.XactAnalysis.Phone))]
[XmlInclude(typeof(CR.Models.XactAnalysis.Email))]
public class Contact
{
[XmlArray("CONTACTMETHODS")]
public List<ContactMethod> ContactMethods { get; set; }
}
public class ContactMethod
{
[XmlElement("PHONE")]
public Phone Phone { get; set; }
[XmlElement("EMAIL")]
public Email Email { get; set; }
}
[XmlRoot("PHONE")]
public class Phone
{
[XmlAttribute("number")]
public string Number { get; set; }
}
[XmlRoot("EMAIL")]
public class Email
{
[XmlAttribute("address")]
public string Address { get; set; }
}
Seems to work swimmingly. 似乎工作顺畅。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.