0
votes

I am very new to C#. I've got XML file. I would like to iterate through all nodes and show values node by node. And at the end, i want to store this value in strings. For example, i want something like this:

First iterate:

  • string name: Belgian Waffles
  • string price: $5.95
  • string description:Two of our famous Belgian Waffles with plenty of real maple syrup
  • string calories: 650

Second iterate:

  • string name: Strawberry Belgian Waffles
  • string price: $7.95
  • string description:Light Belgian waffles covered with strawberries and whipped cream
  • string calories: 900

and etc

 <?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
<food>
    <name>Belgian Waffles</name>
    <price>$5.95</price>
    <description>
   Two of our famous Belgian Waffles with plenty of real maple syrup
   </description>
    <calories>650</calories>
</food>
<food>
    <name>Strawberry Belgian Waffles</name>
    <price>$7.95</price>
    <description>
    Light Belgian waffles covered with strawberries and whipped cream
    </description>
    <calories>900</calories>
</food>
<food>
    <name>Berry-Berry Belgian Waffles</name>
    <price>$8.95</price>
    <description>
    Belgian waffles covered with assorted fresh berries and whipped cream
    </description>
    <calories>900</calories>
</food>
<food>
    <name>French Toast</name>
    <price>$4.50</price>
    <description>
    Thick slices made from our homemade sourdough bread
    </description>
    <calories>600</calories>
</food>
<food>
    <name>Homestyle Breakfast</name>
    <price>$6.95</price>
    <description>
    Two eggs, bacon or sausage, toast, and our ever-popular hash browns
    </description>
    <calories>950</calories>
</food>
</breakfast_menu>
1
Maybe you could start with reading on how this is done. For example : stackoverflow.com/questions/642293/…. And then come back if have specific issues.Sebastien
I'd suggest you deserialize the XML into a C# class first. And it's generally bad practice to model numeric values as strings when appropriate numeric types are available.Jason

1 Answers

0
votes

Here's a console app that does what you want. You'll need to include System.XML.Linq

using System;
using System.Xml.Linq;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {

            var doc = XDocument.Load("C:\\Temp\\menu.xml");

            foreach (XElement xe in doc.Descendants("food"))
            {
                Console.WriteLine("Name:" + xe.Element("name").Value);
                Console.WriteLine("Price:" + xe.Element("price").Value);
                Console.WriteLine("Description:" + xe.Element("description").Value);
                Console.WriteLine("Calories:" + xe.Element("calories").Value);
            }

            Console.Read();
        }
    }
}