Michelle Ann
Michelle Ann

Reputation: 13

Serialize C# objects to specific format

I serialize a Vehicle object with the following code to serialize the object:

        XmlSerializer serializer = new XmlSerializer(typeof(Vehicle));
        using (StreamWriter sw = new StreamWriter(RESULTS_FILE_PATH_))
        using (XmlWriter writer = new XmlTextWriter(sw))
        {
            try
            {
                serializer.Serialize(writer, vehicles[0]);
            }
            catch (Exception exception)
            {
                Console.WriteLine("Exception thrown: " + exception);
            }
        }

The results are as follows:

<?xml version="1.0" encoding="utf-8"?>
    <Model xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <modelYear xmlns="urn:configcompare4g.kp.chrome.com">2014</modelYear> 

            <subdivisionName xmlns="urn:configcompare4g.kp.chrome.com">Buick</subdivisionName><modelId 

    </Model>

I need the format to be like this:

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
  <S:Body>
    <ModelArrayElement xmlns="urn:configcompare4g.kp.chrome.com">
     <model>
        <modelYear>2014</modelYear>
        <subdivisionName>Buick</subdivisionName>
     </model>
    </ModelArrayElement>
  </S:Body>
 </S:Envelope>

Does anyone have any suggestions on how I can produce the proper format?

Upvotes: 1

Views: 327

Answers (2)

Konrad Kokosa
Konrad Kokosa

Reputation: 16878

If your XML output is non-standard and it will be difficult to use any default formatter, I would think about using some templating engine, like RazorEngine, so it would be something like:

string template = 
@"<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">"+
  "<S:Body>"+
  "   <ModelArrayElement xmlns="urn:configcompare4g.kp.chrome.com">"+
  "      <model>"+
  "         <modelYear>@Model.modelYear</modelYear>"+
  "         <subdivisionName>@Model.subdivisionName</subdivisionName>"+
  "      </model>"+
  "    </ModelArrayElement>"+
  "</S:Body>"+
  "</S:Envelope>";

var model = vehicles[0];
string result = Razor.Parse(template, model);

This gives a complete control of output and allows to make more complex logic based on loops, conditionals etc.

Upvotes: -1

bogza.anton
bogza.anton

Reputation: 606

For such a serialization need to use SoapFormatter. Detailed information can be found in the description on MSDN (SoapFormatter).

Upvotes: 4

Related Questions