【发布时间】:2014-09-08 15:44:39
【问题描述】:
我有一个这样的 xml 文档:
<?xml version="1.0" encoding="utf-8" ?>
<Categories>
<Category>
<Name>Fruit</Name>
<Items>
<Item>Apple</Item>
<Item>Banana</Item>
<Item>Peach</Item>
<Item>Strawberry</Item>
</Items>
</Category>
<Category>
<Name>Vegetable</Name>
<Items>
<Item>Carrots</Item>
<Item>Beets</Item>
<Item>Green Beans</Item>
<Item>Bell Pepper</Item>
</Items>
</Category>
<Category>
<Name>Seafood</Name>
<Items>
<Item>Crab</Item>
<Item>Lobster</Item>
<Item>Shrimp</Item>
<Item>Oysters</Item>
<Item>Salmon</Item>
</Items>
</Category>
</Categories>
我希望能够搜索诸如 Category.Name = Fruit 之类的术语并返回 Fruit Items 的列表。
这是我目前开始的不完整代码:
string localPath = Server.MapPath("~/App_Data/Foods.xml");
XmlDocument doc = new XmlDocument();
doc.Load(localPath);
XmlNodeList list = doc.SelectNodes("Categories");
//Do something here to search the category names and get back the list of items.
这是我第一次尝试解析 XML,所以我有点迷茫。注意:我正在开发的应用程序使用 .Net 2.0
【问题讨论】:
-
你熟悉
XPATH听起来可能是你可能需要在你的情况下使用的 -
我不熟悉 XPATH,它是 .Net 2.0 的一部分吗?我对最好的解决方案持开放态度,但希望能举个例子。
-
这里是
SO实际上有大量关于如何搜索或迭代 XML 文件的示例.. -
阅读这里:MSDN on the
XmlNode.SelectNodes Method并尝试提出一个围绕这种方法的解决方案。