0

Say I have the following class:

public class Test
{
    public string FullName { get; set; }

    public int Score { get; set; }

    public DateTime StartDate { get; set; }
}

I then create an instance:

        Test t = new Test
        {
            FullName = "Bob Smith",
            Score = 3.4,
            StartDate = DateTime.Now
        };

I use the XmlSerializer to convert to class to XML

        using (var textWriter = new StringWriter())
        {
            using (XmlWriter xmlWriter = XmlWriter.Create(textWriter))
            {
                var serializer = new XmlSerializer(typeof(Test), CreateOverrides());
                serializer.Serialize(xmlWriter, t);

            }

            xml = textWriter.ToString();
        }

So I end up with this:

<Test>
    <FullName>Bob Smith</FullName>
    <Score>3.4</Score>
    <StartDate>2018-03-12T13:24:19.9284562+00:00</StartDate>
</Test>

What I'd like to do if use some sort of override so I can format the XML. So let's say I'd like to see the following output:

<Test>
    <FullName>First Name: Bob. Surname: Smith</FullName>
    <Score>3.4000</Score>
    <StartDate>2018 (this year) 03 (Spring) 12 (middle period)</StartDate>
</Test>

If there any way I can format or change the XML output based on a type e.g. Date, Int, etc by passing something into the serializer. I've been looking at XmlAttributeOverrides but I can't seem to change the content.

private static XmlAttributeOverrides CreateOverrides()
{
    //Do something here to change the content...
    //if int then change the format to 4 decimal places
    //if date then change the date into a custom format
    //etc   
}

I need to do this via the serializer. I don't want to modify the existing Test class with attributes to ignore and replace xml elements.

Is what I'm trying to do even possible?

Sun
  • 4,458
  • 14
  • 66
  • 108
  • You can use the {get; set;} properties in the class to do the conversion. See posting : https://stackoverflow.com/questions/5096926/what-is-the-get-set-syntax-in-c – jdweng Mar 12 '18 at 14:46
  • No. I need to do this without modifying the class like the question says. – Sun Mar 12 '18 at 19:00
  • Not purely with overrides. The problem is that `XmlSerializer` treats `DateTime` as a primitive type so the nice trick from [Most elegant xml serialization of Color structure](https://stackoverflow.com/a/4322461/3744182) doesn't work. You may need to replace `Test` with a [DTO](https://en.wikipedia.org/wiki/Data_transfer_object). – dbc Mar 13 '18 at 00:58

0 Answers0