Altova Mailing List Archives>Archive Index >comp.text.xml Archive Home >Recent entries >Thread Prev - Re: Append to a file using XML Serialization? Easy way to do this? >Thread Next - Re: Append to a file using XML Serialization? Easy way to do this? Re: Append to a file using XML Serialization? Easy way to do this?To: NULL Date: 7/21/2009 12:18:00 PM RayLopez99 wrote:
> Also does anybody know if there is a 'easier' (or cleaner, less code
> required) way of deserializing than checking each node as per the
> below code?
Yes, certainly, see this example:
class Program
{
static void Main(string[] args)
{
List<Foo> foos = new List<Foo>()
{
new Foo() { Bar = "bar 1", Baz = 1 },
new Foo() { Bar = "bar 2", Baz = 2 },
new Foo() { Bar = "bar 3", Baz = 3 }
};
XmlWriterSettings xrs = new XmlWriterSettings();
xrs.Indent = true;
XmlSerializer ser = new XmlSerializer(typeof(Foo));
using (XmlWriter xr =
XmlWriter.Create(@"..\..\XMLSer1.xml", xrs))
{
xr.WriteStartDocument();
xr.WriteStartElement("Root");
foreach (Foo foo in foos)
{
ser.Serialize(xr, foo);
}
xr.WriteEndElement();
xr.WriteEndDocument();
xr.Close();
}
List<Foo> foos2 = new List<Foo>();
using (XmlReader xr = XmlReader.Create(@"..\..\XMLSer1.xml"))
{
while (xr.Read())
{
if (xr.NodeType == XmlNodeType.Element && xr.Name
== "Foo")
{
Foo foo = (Foo)ser.Deserialize(xr);
foos2.Add(foo);
}
}
xr.Close();
}
foreach (Foo foo in foos2)
{
Console.WriteLine("Bar: {0}; Baz: {1}", foo.Bar, foo.Baz);
}
}
}
public class Foo
{
public string Bar { get; set; }
public int Baz { get; set; }
}
So you simply read through the file with an XmlReader's
while(reader.Read()) loop and each time the reader is positioned on an
element you are interested in you pass the reader to the Deserialize method.
--
Martin Honnen
http://msmvps.com/blogs/martin_honnen/
| ||||||
| Company | Legal | Press | Partners | Careers | Sitemap | Contact Us | Altova Blog | Mobile | Full Site | |||
|
