Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Perhaps this is a cop-out but I was able to make this work using the <code>DataContractSerializer</code> like this:</p> <pre><code>using System; using System.IO; using System.Collections.ObjectModel; using System.Runtime.Serialization; class Program { static void Main() { CarCollection cars = new CarCollection(); cars.Add(new Car { Make = "Ford", Model = "Mustang" }); cars.Add(new Car { Make = "Honda", Model = "Accord" }); cars.Add(new Car { Make = "Toyota", Model = "Tundra" }); using (MemoryStream memoryStream = new MemoryStream()) { DataContractSerializer serializer = new DataContractSerializer(typeof(CarCollection)); serializer.WriteObject(memoryStream, cars); memoryStream.Position = 0; String xml = null; using (StreamReader reader = new StreamReader(memoryStream)) { xml = reader.ReadToEnd(); reader.Close(); } memoryStream.Close(); } } } [CollectionDataContract(Name = "cars")] public class CarCollection : Collection&lt;Car&gt; { } [DataContract(Name = "car")] public class Car { [DataMember(Name = "make")] public String Make { get; set; } [DataMember(Name = "model")] public String Model { get; set; } } </code></pre> <p><strong>Output:</strong></p> <pre><code>&lt;cars xmlns="http://schemas.datacontract.org/2004/07/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;car&gt; &lt;make&gt;Ford&lt;/make&gt; &lt;model&gt;Mustang&lt;/model&gt; &lt;/car&gt; &lt;car&gt; &lt;make&gt;Honda&lt;/make&gt; &lt;model&gt;Accord&lt;/model&gt; &lt;/car&gt; &lt;car&gt; &lt;make&gt;Toyota&lt;/make&gt; &lt;model&gt;Tundra&lt;/model&gt; &lt;/car&gt; &lt;/cars&gt; </code></pre> <p>Notice that the attributes on your types have changed to support the usage of <code>DataContractSerializer</code>. I don't know if this is the direction that you want to go with this but I have found that in almost every case I prefer to use the <code>DataContractSerializer</code> in place of the older <code>XmlSerializer</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload