I know how to deserialize a collection class that is referenced in a
container class as a variable or property using the XmlArray and
XmlArrayItem attributes. What I can't for the life of me figure out is how
to deserialize a collection class that is the top level element of an xml
stream. Hopefully the following example will make sense.
The example below compiles and runs, but it doesn't pick up any of the
children of the collection class. In other words, customers.Count = 0.
Any and all help would be GREATLY appreciated.
Thanks,
Brian Orrell
MethodExperts, LLC
http://www.methodexperts.com
br**********@REMOVETHISTEXTmethodexperts.com
If I have the following xml:
<customers>
<customer id="1" name="Bob" />
<customer id="2" name="Sally" />
<customer id="3" name="Joe" />
</customers>
And the following classes:
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using System.Windows.Forms;
namespace XmlSerializerTest
{
public class App
{
public static void Main(string[] args)
{
CustomerCollection customers;
using (Stream stream =
Assembly.GetExecutingAssembly().GetManifestResourc eStream("XmlSerializerTest
..Customers.xml"))
{
XmlTextReader reader = new XmlTextReader(stream);
XmlSerializer serializer = new XmlSerializer(typeof(CustomerCollection),
new XmlRootAttribute("customers"));
customers = (CustomerCollection)serializer.Deserialize(reader) ;
stream.Close();
}
MessageBox.Show(customers.Count.ToString());
}
public class CustomerCollection : NameObjectCollectionBase, IEnumerable
{
public CustomerCollection()
{
}
public void Add(Customer customer)
{
BaseAdd(customer.Name, customer);
}
public Customer this[int index]
{
get { return (Customer)BaseGet(index); }
}
public new IEnumerator GetEnumerator()
{
return BaseGetAllValues(typeof(Customer)).GetEnumerator() ;
}
}
public class Customer
{
public Customer()
{
}
[XmlAttribute("id")]
public int Id;
[XmlAttribute("name")]
public string Name;
}
}
}
--
Brian Orrell
MethodExperts, LLC
br**********@REMOVETHISTEXTmethodexperts.com
--
Brian Orrell
MethodExperts, LLC
br**********@REMOVETHISTEXTmethodexperts.com