简体   繁体   中英

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:

<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:

[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:

<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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM