Reputation: 293
This is a sample of the xml I´m using:
<?xml version="1.0" encoding="UTF-8"?>
...
<tbody>
<tr class="group">
<td class="team"><span>1</span> <a href="link">Jeans</a></td>
<td class="a">
<p>10</p>
</td>
<td class="b">
<p>20</p>
</td>
<td class="team"><span>1</span> <a href="link">T-shirt</a></td>
<td class="a">
<p>20</p>
</td>
<td class="b">
<p>20</p>
</td>
</tr>
I need to create a object and populate it with the data coming from the xml. I´ve already the class with all the properties needed and I´m using this linq code to read the xml:
var searched = from c in xml.Descendants("tbody").Descendants("tr").Descendants("td").Descendants("a")
from cc in xml.Descendants("tbody").Descendants("tr").Descendants("td") where (cc.Attribute("class").Value == "a")
select new Time
{
name = c.Value,
data = cc.Value
};
Im using this foreach to iterate:
foreach (var item in searched)
{
listBox1.Items.Add(item.name + item.data);
listBox1.Items.Add(" ");
Shouldnt I get a result like this?
Jeans 10 - T-Shirt 10
Instead Im getting: Jeans 10 - Jeans 20 - T-Shirt 10 - T-Shirt 20 -
Is this linq statement wrong? How can I create an object with these values coming from the xml?
Upvotes: 0
Views: 165
Reputation: 9323
I'm not sure what your final goal is, but I'd do something like this:
XElement table = xml.Descendants("tbody").First();
var searched = from c in table.Descendants("tr")
let team = c.Descendants().First()
select new
{
Name = team.Descendants("a").First().Value,
PG = c.Descendants("td").Where(td => (string)td.Attribute("class") == "tc-pg").First().Value,
J = c.Descendants("td").Where(td => (string)td.Attribute("class") == "tc-j").First().Value,
V = c.Descendants("td").Where(td => (string)td.Attribute("class") == "tc-v").First().Value,
// and so on...
};
And then add the items to the list:
foreach (var item in searched)
{
listBox1.Items.Add(string.Format("{0} - {1}", item.Name, item.PG);
listBox1.Items.Add(string.Format("{0} - {1}", item.Name, item.J);
listBox1.Items.Add(string.Format("{0} - {1}", item.Name, item.V);
// and so on...
}
Upvotes: 1