Re: Read XML file using OOP
- From: Martin Honnen <mahotrash@xxxxxxxx>
- Date: Sat, 26 Apr 2008 16:26:19 +0200
Tammy Nejadian wrote:
My xml file call carsXml.xml and it includes below information:
<?xml version="1.0" encoding="utf-8" ?>
<carlot>
<car>
<Make>OldsMobile</Make>
<Model>Cutlas</Model>
<Milage>5000</Milage>
</car>
<car>
<Make>Chevelate</Make>
<Model>Camro</Model>
<Milage>6000</Milage>
</car>
</carlot>
My Class calls carClass however it is not completed. I dont know how to lead that xml file here to read it. The codes I have are:
class carClass
{
//Field
private string _model;
private string _make;
private int _milage;
//properties
public string Model
{
get { return _model; }
set { _model = value; }
}
public string Make
{
get { return _make; }
set {_make = value; }
}
public int Milage
{
get { return _milage; }
set { _milage = value;}
}
}
You could use XML serialization like this:
[XmlRoot(ElementName="carlot")]
public class Carlot
{
public Carlot() { }
private carClass[] cars;
[XmlElement(ElementName = "car")]
public carClass[] Cars
{
get { return cars; }
set { cars = value; }
}
}
public class carClass
{
public carClass() { }
//Field
private string _model;
private string _make;
private int _milage;
//properties
public string Model
{
get { return _model; }
set { _model = value; }
}
public string Make
{
get { return _make; }
set { _make = value; }
}
public int Milage
{
get { return _milage; }
set { _milage = value; }
}
}
then you can load your XML like this:
XmlSerializer ser = new XmlSerializer(typeof(Carlot));
Carlot carlot = (Carlot)ser.Deserialize(XmlReader.Create(@"..\..\XMLFile1.xml"));
foreach (carClass car in carlot.Cars)
{
Console.WriteLine("Make: {0}; Model: {1}; Milage: {2}.", car.Make, car.Model, car.Milage);
}
--
Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
.
- References:
- Read XML file using OOP
- From: Tammy Nejadian
- Read XML file using OOP
- Prev by Date: Windows Presentation Foundation
- Next by Date: Re: Windows Presentation Foundation
- Previous by thread: Read XML file using OOP
- Next by thread: Re: Read XML file using OOP
- Index(es):