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


i have xml-document i'm trying 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 list of fields have type "image" inside of list index 1. there multiple lists in xml have other indexes, want extract ones list index 1. how go about?

i tried do:

foreach (var list in xmldoc.descendants("list")) {    if (list.attribute("index").value == "1") // list    {        foreach (var field in list)        {            if (field.attribute("type") != null && field.attribute("type").value == "image")            {                messagebox.show(field.element("url").value);            }        }    } } 

but giving me error message:

error 2 foreach statement cannot operate on variables of type 'system.xml.linq.xelement' because 'system.xml.linq.xelement' not contain public definition 'getenumerator'

how can resolve this?

you're trying iterate element directly, you'd need iterate descendant field elements, instead of:

foreach (var field in list) 

you want:

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

that said, easier way of doing 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")); 

Comments

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -