Mono: linq to xml: how to select the value from elements

Today I manage to make linq queries in mono and want to share my experiences with you…

To use linq in mono, you need two basic libraries which are:

System.Core and System.Xml.Linq

My first usage is as follows:

/*
 * Created by SharpDevelop.
 * User: cakirh
 * Date: 25.01.2010
 * Time: 15:45
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Linq;
using System.Xml.Linq;

public class MainClass {
 public static void Main() {

 XElement xmlDoc = XElement.Parse(
 @"

<data>

<gpsdata lat='51.052887' lon='4.880805'>
 <name>1</name>
 <cgps id='0' track ='1'/>
</gpsdata>

<gpsdata lat='51.055329' lon='4.900954'>
 <name>2</name>
 <cgps id='1' track ='1'/>
 <cgps id='2' track ='2'/>
 <cgps id='3' track ='5'/>
</gpsdata>

</data>

");

 var titles = (from gpsdata in xmlDoc.Elements("gpsdata").Elements("cgps")
 where gpsdata.Attribute("id").Value == "3"
 select gpsdata.Attribute("track"));

 foreach (var title in titles){
 Console.BackgroundColor=ConsoleColor.White;
 Console.ForegroundColor=ConsoleColor.Black;
 Console.WriteLine(title.ToString());
 Console.ResetColor();

 }

 }
}
<pre>

The Output:

output

References:

[1.] http://geekswithblogs.net/michelotti/archive/2009/12/29/linq-to-xml-with-hierarchical-xml-optional-elements-and-namespaces.aspx

[2.] http://stackoverflow.com/questions/356091/linq-to-xml-how-to-select-the-value-from-elements

[3.] http://forums.silverlight.net/forums/t/157378.aspx
kick it on DotNetKicks.com

About these ads