this is my Xml file that I am trying to desirialize:
<?xml version="1.0"?>
<AddressDirectory>
<Address>
<HouseNo>1</HouseNo>
<StreetName>Pitampura</StreetName>
<City>Delhi</City>
</Address>
<Address>
<HouseNo>4</HouseNo>
<StreetName>Rohini</StreetName>
<City>Delhi</City>
</Address>
</AddressDirectory>
these are my classes:
public class AddressDirectory
{
[XmlElement("Address")]
public List<Address> addressList = new List<Address>();
}
public class Address
{
public int HouseNo { get; set; }
public string StreetName { get; set; }
public string City { get; set; }
}
this is my main:
XmlSerializer deserializer = new XmlSerializer(typeof(AddressDirectory));
TextReader reader = new StreamReader(@"D:\myXml.xml");
object obj = deserializer.Deserialize(reader);
AddressDirectory XmlData = (AddressDirectory)obj;
reader.Close();
this is how I access the elements that must have ben saved in the list:
XmlData.addressList[0].HouseNo;
XmlData.addressList[0].StreetName;
XmlData.addressList[0].City;
or in a loop I access like this:
for (int i = 1; i < 10; i++)
{
Console.Write("house number for {0}: ", i);
Console.WriteLine(XmlData.addressList[i].HouseNo);
Console.Write("Street Name for {0}: ", i);
Console.WriteLine(XmlData.addressList[i].StreetName);
Console.Write("City for {0}: ", i);
Console.WriteLine(XmlData.addressList[i].City);
}
this is the error that I am getting when I execute the program:
Index was out of range. Must be non-negative and less than the size of the collection.
I guess this is because we are not adding anything in the list. Because to add to the list we have to use List.Add() somewhere in the main.
No comments:
Post a Comment