我正在尝试将一些XML发送给第三方,我需要发送的元素的格式如下所示:
<CONTACT>
<CONTACTMETHODS>
<PHONE number='202-555-1234' />
<EMAIL address='myname@gmail.com' />
</CONTACTMETHODS>
</CONTACT>
我在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; }
}
发送到字符串的XML是:
<CONTACT>
<CONTACTMETHODS>
<ContactMethod xsi:type="Phone" number="202-555-1234" />
<ContactMethod xsi:type="Email" address="myname@gmail.com" />
</CONTACTMETHODS>
</CONTACT>
如何让序列化程序创建我需要的XML?
编辑:根据要求,以下是序列化对象的代码:
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;
}
答案 0 :(得分:1)
[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; }
}
好像在游泳。