hi all, just having a play with xml and c# before putting them to some real work
. I have been using a book that shows how to use XmlSerializer to create an xml object then write that object to file. The code is as follows
This works fine but the book does not then tell you how to add another object to the xml file? So i tried..
Code:
// (1) Create array of objects to be serialized
Movies[] films = {new Movies(5,"Citizen Kane","Orson Welles",
"Y", 1941,1 ),
new Movies(6,"Casablanca","Michael Curtiz",
"Y", 1942,2), new Movies(10,"Lord Of The Rings","Gandelf",
"Y", 2005,1) };
// (2) Create serializer
// This attribute is used to assign name to XML root element
xRoot = new XmlRootAttribute();
xRoot.ElementName = "films";
xRoot.Namespace = "[URL unfurl="true"]http://www.myxml.com";[/URL]
xRoot.IsNullable = true;
// Specify that an array of movies types is to be serialized
XmlSerializer xSerial = new XmlSerializer(typeof(Movies[]), xRoot);
string filename = @"c:\oscarwinner_xml\oscarwinners.xml";
// (3) Stream to write XML into
TextWriter writer = new StreamWriter(filename);
xSerial.Serialize(writer, films);
This works fine but the book does not then tell you how to add another object to the xml file? So i tried..
Code:
Movies mvs = new Movies(ID, mTitle, mDirector, mbestPicture, mYear, rank);
// Specify that an array of movies types is to be serialized
XmlSerializer xSerial = new XmlSerializer(typeof(Movies), xRoot);
string filename = @"c:\oscarwinner_xml\oscarwinners.xml";
// (3) Stream to write XML into
TextWriter writer = new StreamWriter(filename, true);
xSerial.Serialize(writer, mvs);
[code]
unfortunately this method also adds another top level node (films) before and after the record. So... how do I add another object to the xml file? Or do i just overwrite the file?
Any help appreciated.
Age is a consequence of experience