Question

I need to parse an XML document, but I can't use XDocument. Without going into technical details of why I can't use it, how can I accomplish this? I can, however, use XmlDocument and other methods.

var restaurants = from r in xdoc.Root.Elements("Restaurant")
                    select new {
                    Name = (string)r.Element("name"),
                    Location = (string)r.Element("location")
                };
foreach(var restaurant in restaurants)
{
    String name = restaurant.Name; 
    String location = restaurant.Location;
}
Was it helpful?

Solution

Assuming the XML file looks like the one you've described in your previous question:

<Restaurants>
    <Restaurant>
      <name>test</name>
      <location>test</location>
   </Restaurant>
   <Restaurant>
      <name>test2</name>
      <location>test2</location>
   </Restaurant>
</Restaurants>

Yes, I've added root Restaurants element to make it a valid XML file.

You can use XML Deserialization to get objects from that XML:

Classes

public class Restaurant
{
    [XmlElement(ElementName = "name")]
    public string Name { get; set; }
    [XmlElement(ElementName = "location")]
    public string Location { get; set; }
}

public class Restaurants
{
    [XmlElement(ElementName="Restaurant")]
    public List<Restaurant> Items { get; set; }
}

Deserialization

var serializer = new XmlSerializer(typeof(Restaurants));
var restaurants = serializer.Deserialize(File.OpenRead("Input.txt"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top