有没有办法让xml序列化器转换以下内容:

class Mail
{
    public string Subject = "sub1";
}


转换为以下XML模式:

<Mail>
    <MailSubject>
        <Subject>sub1</Subject>
    </MailSubject>
</Mail>


那就是我想在不使用以下子类的情况下将xmlElement包装在新的xmlElement组中:

class Mail
{
    public MailSubject MailSubject = new MailSubject();
}

class MailSubject
{
    public string Subject = "sub1";
}


我的xml格式来自第3方,我正在尝试使其能够使我们的对象有意义并易于使用,同时仍保持其xml模式。

最佳答案

正如Buh Buh所说,实现IXmlSerializable的唯一方法。可能的实现如下所示:

public class Mail : IXmlSerializable
{
    public string Subject;

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        bool isEmpty = reader.IsEmptyElement;

        reader.ReadStartElement();
        if (isEmpty) return;

        isEmpty = reader.IsEmptyElement;
        reader.ReadStartElement();
        if (isEmpty)
        {
            reader.ReadEndElement();
            return;
        }

        Subject = reader.ReadString();

        reader.ReadEndElement();
        reader.ReadEndElement();
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        writer.WriteStartElement("MailSubject");
        writer.WriteElementString("Subject", Subject);
        writer.WriteEndElement();
    }
}

09-16 15:31