【问题标题】:Searching through XML to find a list of items通过 XML 搜索以查找项目列表
【发布时间】: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 并尝试提出一个围绕这种方法的解决方案。

标签: c# xml .net-2.0


【解决方案1】:

我建议您阅读有关 XPath 的信息,因为您仅限于 .NET 2.0,此外,即使在更一般的上下文中(不仅限于 .NET 平台),XPath 对于使用 XML 也非常有用。

在这种特殊情况下,XPath 变得有用,因为 SelectNodes()SelectSingleNode() 方法接受 XPath 字符串作为参数。例如,获取与类别名称"Fruit"对应的所有&lt;Item&gt;

string localPath = Server.MapPath("~/App_Data/Foods.xml");
XmlDocument doc = new XmlDocument();
doc.Load(localPath);
XmlNodeList items = doc.SelectNodes("Categories/Category[Name='Fruit']/Items/Item");
foreach(XmlNode item in items)
{
    Console.WriteLine(item.InnerText);
}

您可以将 XPath 视为路径,类似于 Windows 资源管理器中的文件路径。我将尝试仅解释与上述示例中的常见路径表达式不同的位,尤其是这一位:

...\Category[Name='Fruit']\...

方括号内的表达式是一个过滤器,表示搜索具有子节点&lt;Name&gt;&lt;Category&gt; 节点等于"Fruit"

【讨论】:

    【解决方案2】:

    你走在正确的道路上。但是,您需要先加载“类别”节点,然后才能获取它的子节点。

    我添加了一个过滤器以仅返回名称为“Fruit”的节点。

    XmlNode cat = doc.SelectSingleNode("Categories");
    var list = cat.SelectNodes("Category").Cast<XmlNode>()
                  .Where(c => c.SelectSingleNode("Name").InnerText == "Fruit");
    
    foreach ( XmlNode item in list )
    {
        // process each node here
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-13
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 2013-07-28
      • 1970-01-01
      相关资源
      最近更新 更多