i have the following xml file
<?xml version="1.0" encoding="utf-8"?>
<Users>
<User>
<Name>John Smith</Name>
<test>
<Date>23.05.2011</Date>
<points>33</points>
</test>
<test>
<Date>22.06.2011</Date>
<points>29</points>
</test>
</User>
</Users>
and i would like to use linq to extract the dates and the points of the tests where username is "John Smith"..
how would i build my linq ?
i have done the following, but is not working as i wish :
XElement main = XElement.Load(@"users.xml");
string t = "John Smith";
var v = from user in main.Elements("User")
where t == users.Element("Name").Value
select users;
MessageBox.Show(v.First().Element("Date").Value.ToString());
I'm not sure what format you want the output to be, but this samples code should get the date and points. This projects the results into an anonymous type:
class Program
{
static void Main(string[] args)
{
XElement main = XElement.Load(@"users.xml");
var results = main.Descendants("User")
.Descendants("Name")
.Where(e => e.Value == "John Smith")
.Select(e => e.Parent)
.Descendants("test")
.Select(e => new { date = e.Descendants("Date").FirstOrDefault().Value, points = e.Descendants("points").FirstOrDefault().Value });
foreach (var result in results)
Console.WriteLine("{0}, {1}", result.date, result.points);
Console.ReadLine();
}
}
And the output is:
23.05.2011, 33
22.06.2011, 29
Try this out
class Program
{
static void Main(string[] args)
{
XElement main = XElement.Parse(
@"<Users>
<User>
<Name>John Smith</Name>
<test>
<Date>23.05.2011</Date>
<points>33</points>
</test>
<test>
<Date>22.06.2011</Date>
<points>29</points>
</test>
</User>
</Users>");
var users =
from m in main.Elements("User")
where (string)m.Element("Name") == "John Smith"
select (m.Descendants("test").Descendants("Date").FirstOrDefault().Value);
foreach (var user in users)
Console.WriteLine(user);
Console.ReadLine();
}
}
Regards
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With