Ben313
Ben313

Reputation: 1668

Load in a simple list of objects defined in xml as an object in C#

I am a university student taking a HCI design course, and using C# and WPF for the first time. I have read a little about xml, and it seems like a good way to get input for use in my program. I have an XML file i made that contains a list of houses and there peramaters, like so:

<house>
    <Price>400000</price>
    <neighborhood>BrentWood</neighborhood>
    <description>This is a so and so house, located...</description>
</house>
<house>
    <Price>300000</price>
    <neighborhood>BrentWood</neighborhood>
    <description>This is a so and so house, located...</description>
</house>

And i have a house class like so:

public class house{
    public house(int price, string neighborhood, string description){
        this.price = price;
        this.neighborhood = neighborhood;
        this.description = description;
    }
    public int price;
    public string neighborhood;
    public string description;
}

I have read a little about xml, but i cant seems to find a tutorial to make a function that takes the xml file as input, and returns a List of newly created house objects. Can anyone show me how this is done? Or maybe suggest a better way of defining the house objects in a file, and loading them as house objects?

Upvotes: 1

Views: 1668

Answers (4)

Niranjan Singh
Niranjan Singh

Reputation: 18290

Check these link that help you read the XML file in C# and better guide you which way is good to read it fast:
How to read XML from a file by using Visual C#
Using XML in C# in the simplest way
Reading xml fast

First open your file with XmlTextReader class.

XmlTextReader reader = new XmlTextReader ("books.xml");

After you create the XmlTextReader object, use the Read method to read the XML data. The Read method continues to move through the XML file sequentially until it reaches the end of the file, at which point the Read method returns a value of "False."

To process the XML data, each record has a node type that can be determined from the NodeType property.

while (reader.Read()) 
{
    switch (reader.NodeType) 
    {
        case XmlNodeType.Element: // The node is an element.
            Console.Write("<" + reader.Name);
   Console.WriteLine(">");
            break;
  case XmlNodeType.Text: //Display the text in each element.
            Console.WriteLine (reader.Value);
            break;
  case XmlNodeType. EndElement: //Display the end of the element.
            Console.Write("</" + reader.Name);
   Console.WriteLine(">");
            break;
    }
}

On the place of Console.WriteLine fill your house object with reader.name or properties that you have created in the xml file..

Check these for reading XML file from Linq.
LINQ to read XML
Reading XML documents using LINQ to XML

Check this MSDN tutorial .NET Language-Integrated Query for XML Data

Create Properties in your class rather than creating public elements and constructor for better implementation.

Upvotes: 1

TySu
TySu

Reputation: 131


1. Correct your tags. You cannot have opening "Price" and closing "price" they do not match and it will cause errors.
2. You have to have root element in your XML. Your document should start with some element and close with it (root can be houses).
3. You can load objects using Linq 2 XML:

XElement element = XElement.Parse(...) // or XDocument.Load
List<house> myList = (from item in element.Descendants("house")
                      select new house(Convert.ToInt32(item.Element("price").Value),
                                       item.Element("neighborhood").Value,
                                       item.Element("description").Value)).ToList();

Upvotes: 0

Chris Fulstow
Chris Fulstow

Reputation: 41902

This should get you started using LINQ to XML:

XDocument housesXml = XDocument.Load("houses.xml");

List<House> houses =
    housesXml.Root.Elements("house")
    .Select(h => new House(
        int.Parse(h.Element("price").Value),
        (string) h.Element("neighborhood"),
        (string) h.Element("description")
    ))
    .ToList();

(Also, wrap your <house> elements in an outer <houses></houses> root tag, and take care to match case, <Price></price> should be <price></price>)

Upvotes: 2

JayP
JayP

Reputation: 809

Or you could use the XmlTextReader class

Upvotes: 0

Related Questions