Search Results

Search found 1 results on 1 pages for 'roomaroo'.

Page 1/1 | 1 

  • XmlSerialize a custom collection with an Attribute

    - by roomaroo
    I've got a simple class that inherits from Collection and adds a couple of properties. I need to serialize this class to XML, but the XMLSerializer ignores my additional properties. I assume this is because of the special treatment that XMLSerializer gives ICollection and IEnumerable objects. What's the best way around this? Here's some sample code: using System.Collections.ObjectModel; using System.IO; using System.Xml.Serialization; namespace SerialiseCollection { class Program { static void Main(string[] args) { var c = new MyCollection(); c.Add("Hello"); c.Add("Goodbye"); var serializer = new XmlSerializer(typeof(MyCollection)); using (var writer = new StreamWriter("test.xml")) serializer.Serialize(writer, c); } } [XmlRoot("MyCollection")] public class MyCollection : Collection<string> { [XmlAttribute()] public string MyAttribute { get; set; } public MyCollection() { this.MyAttribute = "SerializeThis"; } } } This outputs the following XML (note MyAttribute is missing in the MyCollection element): <?xml version="1.0" encoding="utf-8"?> <MyCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <string>Hello</string> <string>Goodbye</string> </MyCollection> What I want is <MyCollection MyAttribute="SerializeThis" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <string>Hello</string> <string>Goodbye</string> </MyCollection> Any ideas? The simpler the better. Thanks.

    Read the article

1