2

Is there any way to get the xml serializer to convert the following:

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

into the following XML schema:

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

That is I want to wrap the xmlElement in a new xmlElement group without using the following sub class:

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

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

My xml format comes from a 3rd party and I'm trying to make it so that our objects make sense and are easily usable while still keeping to their xml schema.

0

2 Answers 2

1

As Buh Buh said, the only way to do this by implementing IXmlSerializable. A possible implementation would look like this:

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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you make Mail implement IXmlSerializable, then you can have any xml you like. But this might just create more work than you really want to do.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.