Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read xml file using linq

Tags:

c#

xml

linq

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()); 
like image 226
brandon Avatar asked Aug 28 '11 18:08

brandon


2 Answers

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
like image 83
JohnD Avatar answered Oct 06 '22 05:10

JohnD


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

like image 35
GoRoS Avatar answered Oct 06 '22 05:10

GoRoS