循环访问具有特定索引的元素内的元素列表

本文关键字:元素 列表 索引 访问 循环 | 更新日期: 2023-09-27 17:55:26

我有一个XML文档,我正在尝试从中提取数据。

<folder>
<list index="1">
<item index="1" >
<field type="IMAGE">
<url>https://www.test.com/0001.png</url>
</field>
</item>
<item index="2">
<field type="IMAGE">
<url>https://www.test.com/0002.png</url>
</field>
</item>
</list>

等。。。

我正在尝试获取索引为 1 的列表内具有"IMAGE"类型的所有字段的列表。xml 中有多个列表,但它们还有其他索引,但我只想从索引为 1 的列表中提取这些列表。我该怎么做?

我尝试做:

foreach (var list in xmlDoc.Descendants("list"))
{
   if (list.Attribute("index").Value == "1") // GET THE LIST
   {
       foreach (var field in list)
       {
           if (field.Attribute("type") != null && field.Attribute("type").Value == "IMAGE")
           {
               MessageBox.Show(field.Element("url").Value);
           }
       }
   }
}

但这给了我一条错误消息:

错误 2 foreach 语句无法对类型的变量进行操作 "System.Xml.Linq.XElement",因为"System.Xml.Linq.XElement"没有 包含"获取枚举器"的公共定义

我该如何解决这个问题?

循环访问具有特定索引的元素内的元素列表

您尝试直接迭代一个元素,您需要迭代其后代字段元素,因此而不是:

foreach (var field in list)

你想要:

foreach (var field in list.Descendants("field"))

也就是说,执行此操作的一种更简单的方法是使用 LINQ:

var urls = xmlDoc.Descendants("list")
    .Where(e => (int)e.Attribute("index") == 1)
    .Descendants("field")
    .Where(e => (string)e.Attribute("type") == "IMAGE")
    .Select(e => (string)e.Element("url"));

因为问题有xpath标签:)

//list[@index="1"]//field[@type="IMAGE"]/url/text()