【问题标题】:Iterating through all nodes in XML遍历 XML 中的所有节点
【发布时间】:2020-09-01 07:31:09
【问题描述】:

我对 C# 很陌生。我有 XML 文件。我想遍历所有节点并逐节点显示值。最后,我想将此值存储在字符串中。例如,我想要这样的东西:

第一次迭代:

  • 字符串名称:比利时华夫饼
  • 字符串价格:5.95 美元
  • 字符串描述:我们著名的两个比利时华夫饼,加入大量真正的枫糖浆
  • 串卡路里:650

第二次迭代:

  • 字符串名称:草莓比利时华夫饼
  • 字符串价格:7.95 美元
  • 字符串描述:轻薄的比利时华夫饼,上面覆盖着草莓和生奶油
  • 串卡路里:900

等等

 <?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>

【问题讨论】:

标签: c# xml


【解决方案1】:

这是一个控制台应用程序,可以满足您的需求。 您需要包含 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();
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多