c# - 遍历 XML 中的所有节点
问题描述
我对 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>
解决方案
这是一个控制台应用程序,可以满足您的需求。您需要包括 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();
}
}
}
推荐阅读
- typescript - 为什么 TypeScript 的箭头函数返回的不仅仅是一个显式的 void,但函数上的错误却是一样的?
- ckeditor - CKEditor5 - 源格式/布局
- python - 继续获取 TypeError: unsupported operand type(s) for *=: 'function' and 'float' error for pythagorean Triplet
- html - 响应式网页设计布局
- vue.js - 在 vuetify 2.x 中显示突出显示的列表项
- flutter - 如何在页面指示器中导航到下一页
- linux - 管道 sox 输出到 aplay
- postgresql - 在 SQLAlchemy 的 hybrid_property 中使用(加入和选择)Postgres CTE
- reactjs - 两个巢反应路线如何正确?
- codeblocks - 如何修复 Code::Blocks 错误 0xc000007b