在C#中,如何将派生对象序列化为此XML?

时间:2014-07-21 22:41:22

标签: c# xml serialization

我正在尝试将一些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;
}

1 个答案:

答案 0 :(得分:1)

我正以错误的方式思考它。我没有使用Phone和Email派生的抽象类,而是这样做了:

[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; }
}

好像在游泳。