Iterating through a list of elements inside an element with a specific index

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>

etc...

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?

I tried to do:

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:

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'

How can I resolve this?

-------------Problems Reply------------

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)

You want:

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

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

Because the question has xpathtag :)

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

Category:c# Views:1 Time:2018-11-12
Tags: linq xml xpath

Related post

  • Removal of elements during iteration through a list - safety 2010-01-27

    I was wondering if something like this is safe... // Iterating through a <list> while ( iter != seq.end()) { if ( test ) { iter = seq.erase( iter ); } else { ++iter; } I know that iterating through a vector in this way would invalidate the iter

  • Iterating through a list in Python 2009-10-15

    I am trying to iterate through a list and take each part of the list, encode it and join the result up when it is all done. As an example, I have a string which produces a list with each element being 16 characters in length. message = (u'sixteen-let

  • iterating through a list in haskell 2012-01-26

    I have a list of list of characters ::[[Char]]. I need to iterate both over the list of strings and also over each character in each string. Say, my list is present in this variable. let xs Please suggest an easy way to iterate. --------------Solutio

  • Iterating through a list being modified by another thread 2012-03-28

    I'm new to multithreaded programming, and have a question. How do I get each thread to iterate through all the elements in a list being added to by a different thread? Here's a simple program to demonstrate. I have a single list of integers, and 10 t

  • .NET - What is the best/correct way to iterator through a List and remove misc. members? 2009-10-25

    In C++ using std::list, this is a simple matter of erasing what an iterator is pointing to (the erase statement returns the next valid member of the list). What's the best way to iterator through a list and remove members that match a certain criteri

  • How to collect all the VELatLong objects iterating through a list of polygons? 2011-08-13

    this question should be quite simple, but I haven't been able to figure it out. I want to collect all the VELatLong objects iterating through a list of polygons in JavaScript in order to use the SetMapView() method. So far I have been able to do with

  • Actionscript 3 writing a XML element inside a another with code 2011-09-22

    I'm having a bit of problems with simple XML coding. I'm using a simple flash application to write a XML containing customer data (simple stuff, like phone number, name, email, etc). I understand how to write XML manually, but my issue comes when I w

  • Block Level Elements inside Inline elements 2009-11-11

    This question already has an answer here: Is it wrong to change a block element to inline with CSS if it contains another block element? 9 answers The W3C Validator tells me I can't put block-level elements inside inline elements. Makes sense... but

  • get html element inside another element in javascript 2011-02-08

    Hi I am creating dynamic div elements , let say 4 div are there . div1,div2,div3,div4. each div has set of radio buttons rad1,rad2,rad3,rad4 . see as follows. div1 ->rad1,rad2,rad3,rad4 groupName=rd1 ->end div1 div2 ->rad1,rad2,rad3,rad4 gro

  • Iterating through a list based on the value of an Id element inside the list in c# 2011-06-20

    I have another question that's connected with my class: public class Parent { public IList<ParentDetail> ParentDetails { get { return _ParentDetails; } } private List<ParentDetail> _ParentDetails = new List<ParentDetail>(); public P

  • Logic of iterating through a list. Element "flickering" 2009-11-01

    [SOLVED]: Applying proper list iteration procedure fixed problem. (Shown below) I currently have a program in which elements of a list are iterated through and erased if they meet certain conditions. Due to the nature of the program, this can be visu

  • Problems removing elements from a list when iterating through the list 2010-08-23

    I have a loop that iterates through elements in a list. I am required to remove elements from this list within the loop based on certain conditions. When I try to do this in C#, I get an exception. apparently, it is not allowed to remove elements fro

  • Loop problem while iterating through a list and removing recurring elements 2011-08-20

    This question already has an answer here: Modifying list while iterating 7 answers I want to iterate through a list, and remove the items that count more than once, so they don't get printed repeatedly by the for loop. However, some items appearing o

  • OCaml: Iterating through a list and skipping elements if of the wrong constructor 2011-09-30

    This may seem like an odd thing to do, and you're certainly welcome to suggest a better way to do it. Here's my goal: I want to scroll through each element of a list passed into a function. If it's of constructor Y, then I want to call some function

  • Iterating through a list of points in C++ 2012-04-18

    I have a point3 struct that takes 3 floats x, y, z (3-D space coordinates). I'm trying to write a function that translates the x, y, z values of each element in a list of points. I'm new to C++ so I don't think I wrote the iterator correctly, can any

  • Iterating through a list in reverse order in java 2010-01-20

    I'm migrating a piece of code to make use of generics. One argument for doing so is that the for loop is much cleaner than keeping track of indexes, or using an explicit iterator. In about half the cases, the list (an ArrayList) is being iterated in

  • Performance: Iterating through a List in Java 2010-04-15

    Is it slower to iterate through a list in Java like this: for (int i=0;i<list.size();i++) { .. list.get(i) } as opposed to: for (Object o: list) { ... o } --------------Solutions------------- I assume you ask out of pure curiosity and won't cite K

  • Design pattern? Function iterating through a list in search of the first {success} result 2010-07-19

    I've got a coding problem in Erlang that is probably a common design pattern, but I can't find any info on how to resolve it. I've got a list L. I want to apply a function f to every element in L, and have it run across all elements in L concurrently

  • Iterating through a list made up of a custom Class. How do I do it? C++ 2011-03-24

    I am working on an assignment for my Operating Systems class. I am to simulate how a schedular works with Processes. I have a Process class which holds all the information about the processes. I also have a class called scheduler which holds two Proc

  • Iterating through a list, avoiding ConcurrentModificationException when removing in loop 2008-10-21

    We all know you can't do this: for (Object i : l) { if (condition(i)) l.remove(i); } ConcurrentModificationException etc... this apparently works sometimes, but not always. Here's some specific code: public static void main(String[] args) { Collectio

  • Iterating through two lists in Django templates 2010-03-10

    I want to do the below list iteration in django templates: foo = ['foo', 'bar']; moo = ['moo', 'loo']; for (a, b) in zip(foo, moo): print a, b django code: {%for a, b in zip(foo, moo)%} {{a}} {{b}} {%endfor%} I get the below error when I try this: Fi

  • VBA - Access 03 - Iterating through a list box, with an if statement to evaluate 2010-05-31

    So I have a one list box with values like DeptA, DeptB, DeptC & DeptD. I have a method that causes these to automatically populate in this list box if they are applicable. So in other words, if they populate in this list box, I want the resulting

  • Is there a way to populate a dataGridView from multiple lists without iterating through the lists? 2011-06-30

    Say I have three lists containing multiple objects. Lets also assume they each contain the same number of items. For example Dim mylist1 as List(Of Integer) Dim myList2 as List(Of Integer) Dim myList3 as List(Of Integer) ... ... <lists are populat

  • Update entity columns iterating through col list using LINQ 2011-08-29

    I can get column list from the table using LINQ like this: OrderDataContext ctx = new OrderDataContext(); var cols = ctx.Mapping.MappingSource .GetModel( typeof( OrderDataContext ) ) .GetMetaType( typeof( ProductInformation ) ) .DataMembers; This giv

  • Iterating through a list of commands in a file in Shell Programming 2009-04-13

    I have a file containing a list of unix commands like "ls -la /etc/passwd". I want to iterate through this list of commands, and take appropriate action. Currently, my code is something like: #!/bin/bash clear for cmds in `cat /tmp/cmd` do if [ $cmds

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.083 (s). 11 q(s)