遍历具有特定索引的元素内的元素列表 [英] Iterating through a list of elements inside an element with a specific index

查看:96
本文介绍了遍历具有特定索引的元素内的元素列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML文档,正试图从中提取数据.

I have an XML-document that I'm trying to extract data from.

<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的那些.我该怎么办?

I'm trying to get a list of all the fields that have the type "IMAGE" inside of the list with the index 1. There are multiple lists in the xml but they have other indexes, but I only want to extract the ones from the list with index 1. How do I go about?

我试图做:

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);
           }
       }
   }
}

但这给我一个错误消息:

but this is giving me an error message:

错误2 foreach语句无法对类型为变量的变量进行操作 'System.Xml.Linq.XElement',因为'System.Xml.Linq.XElement'不 包含"GetEnumerator"的公共定义

Error 2 foreach statement cannot operate on variables of type 'System.Xml.Linq.XElement' because 'System.Xml.Linq.XElement' does not contain a public definition for 'GetEnumerator'

我该如何解决?

推荐答案

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

You're trying to iterate an element directly, you'd need to iterate its descendant field elements, so instead of:

foreach (var field in list)

您要:

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

也就是说,一种更简单的方法是使用LINQ:

That said, an easier way of doing this is to make use of 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"));

这篇关于遍历具有特定索引的元素内的元素列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆