A simple example that allows you to read data from an xml document using C# and LINQ
Suppose you have a file like this:
Code:
<?xml version="1.0" ?>
<?xml-stylesheet type="text/xsl" href="books.xsl" ?>
<books>
<book>
<title>Programming in XML</title>
<author>Marc Vince</author>
<pages>348</pages>
<category>Programming</category>
</book>
<book>
<title>Programming in C#</title>
<author>Loren Gallipyos</author>
<pages>234</pages>
<category>Programming</category>
</book>
<book>
<title>Android</title>
<author>Norman Bert</author>
<pages>419</pages>
<category>Operating Systems</category>
</book>
<book>
<title>Linux</title>
<author>Hurth Francy</author>
<pages>294</pages>
<category>Operating Systems</category>
</book>
<book>
<title>WordPress</title>
<author>Milena Zarch</author>
<pages>364</pages>
<category>CMS</category>
</book>
<book>
<title>Joomla!</title>
<author>Denise Patrics</author>
<pages>163</pages>
<category>CMS</category>
</book>
<book>
<title>jQuery</title>
<author>Teresa Curtis</author>
<pages>349</pages>
<category>Programming</category>
</book>
</books>
Code:
using System;
using System.Linq;
using System.Xml.Linq;
namespace ConsoleApplications
{
class TestLinqInCSharp
{
static void Main(string[] args)
{
XElement books = XElement.Load(@"books.xml", LoadOptions.PreserveWhitespace);
var booksQuery =
from book in books.Elements()
select book;
foreach (string n in booksQuery)
Console.WriteLine("{0}",n);
}
}
}
Result:
Programming in XML
Marc Vince
348
Programming
Programming in C#
Loren Gallipyos
234
Programming
Android
Norman Bert
419
Operating Systems
Linux
Hurth Francy
294
Operating Systems
WordPress
Milena Zarch
364
CMS
Joomla!
Denise Patrics
163
CMS
jQuery
Teresa Curtis
349
Programming