I understand that this is a couple of years late, but I was able to achieve the structure you wanted just by using XmlElementAttribute .
I discovered this using XSD.exe to generate schema definitions from xml and generate .Net code from xsd files. As far as I know, this works in .Net from 3.5 to 4.6.
Here is the class definition I used:
public class books { public int bookNum { get; set; } public class book { public string name { get; set; } public class record { public string borrowDate { get; set; } public string returnDate { get; set; } } [XmlElement("record")] public record[] records { get; set; } } [XmlElement("book")] public book[] allBooks { get; set; } }
And here is the LinqPad snippet that illustrates serialization / deserialization (based on David Colwell's code snippet, thanks BTW for a hint on how to exclude the spec, this was exactly what I was looking for):
books bks = new books(); books bks2 = null; bks.bookNum = 2; bks.allBooks = new books.book[] { new books.book { name="book 1", records = new books.book.record[] { new books.book.record{borrowDate = DateTime.Now.ToString(), returnDate = DateTime.Now.ToString()} } }, new books.book { name="book 2", records = new books.book.record[] { new books.book.record{borrowDate = DateTime.Now.ToString(), returnDate = DateTime.Now.ToString()}, new books.book.record{borrowDate = DateTime.Now.ToString(), returnDate = DateTime.Now.ToString()}} }, }; string xmlString; System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(books)); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = new UnicodeEncoding(false, false); // no BOM in a .NET string settings.Indent = true; settings.OmitXmlDeclaration = true; XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); // exclude xsi and xsd namespaces by adding the following: ns.Add(string.Empty, string.Empty); using(StringWriter textWriter = new StringWriter()) { using(XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings)) { serializer.Serialize(xmlWriter, bks, ns); } xmlString = textWriter.ToString(); //This is the output as a string } xmlString.Dump(); // Deserialize the xml string now using ( TextReader reader = new StringReader(xmlString) ) { bks2 = ( books )serializer.Deserialize(reader); } bks2.Dump();
This created XML that can be serialized and deserialized without implementing IXmlSerializable, for example:
<books> <bookNum>2</bookNum> <book> <name>book 1</name> <record> <borrowDate>2/2/2016 5:57:25 PM</borrowDate> <returnDate>2/2/2016 5:57:25 PM</returnDate> </record> </book> <book> <name>book 2</name> <record> <borrowDate>2/2/2016 5:57:25 PM</borrowDate> <returnDate>2/2/2016 5:57:25 PM</returnDate> </record> <record> <borrowDate>2/2/2016 5:57:25 PM</borrowDate> <returnDate>2/2/2016 5:57:25 PM</returnDate> </record> </book> </books>
vbigham
source share