我对C#非常陌生。我有XML文件。我想遍历所有节点并逐节点显示值。最后,我想将此值存储在字符串中。例如,我想要这样的东西:
第一次迭代:
第二次迭代:
等等
<?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>
答案 0 :(得分:0)
这是一个控制台应用程序,可以满足您的需求。 您需要包含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();
}
}
}