- Home /
XElement loop through elements in IEnumerator
I'm trying to download an XML file from a website, parse it into XElement and then read the information inside the document. I put it all in an IEnumerator and used the WWW method to get the information. However when I try to use a foreach the code reads no elements with the name "Name" however there are at least 10.
IEnumerator GetFile() {
print ("getting file");
WWW www = new WWW(url);
yield return www;
print (www.text);
XElement x = XElement.Parse(www.text);
//x.Save(@"D:\doc.xml");
foreach(XElement name in x.Elements("Name"))
{
print ("BOO");
}
print ("END");
}
It gets the document, and if I uncomment the Save function it definitely saves the correct document, however the loop does not work. Here's an example of what the XML file looks (since you need an account to get it).
<Data>
<Results>
<Item>
<ID>3412</ID>
<Name>The Second Sword of Tyr</Name>
<Cost>5,000 gp</Cost>
<Level>10</Level>
<Rarity>Rare</Rarity>
<Category>Weapon</Category>
<SourceBook>Dungeon Magazine 196</SourceBook>
<LevelSort>10</LevelSort>
<CostSort>5000</CostSort>
</Item>
Any help here?
Answer by wibble82 · Mar 10, 2014 at 09:01 AM
The 'Elements' function only looks at child elements, it doesn't search the whole file. So if you just loaded the doc you'd be looking at the 'Data' take I think (try debug logging out x.Name).
You could do that just with nested for loops, or use Linq queries with the 'SelectMany' operator. There may be a funky XElement function to do searches in child nodes, but I don't know of it :)
If you add the 'usings' for xml linq operations (I think System.Linq and System.Xml.Linq), your query would be something like:
//linq query to extract all name elements
IEnumerable<XElement> name_elements = x.Elements("Data") //get all data elements
.SelectMany(a = > a.Elements("Results")) //aggregate together all their 'Results' elements
.SelectMany(a=> a.Elements("Item") //aggregate together all their 'Item' Elements
.Where(a => a.Name=="Name") //extract elements called "Name"
foreach(XElement e in name_elements)
{
//bla
}
Note: that assumes you could have multiple data, results and item elements. Simpler if you don't, but I reckon you can work that one out.
Your answer
Follow this Question
Related Questions
suspend a function time to recover a data C# 2 Answers
Coroutine needed here? 1 Answer
WWW, RESTful Service, and Threading 1 Answer
Yielding with WWW in Editor 9 Answers
Coroutines and Static function 1 Answer