XDocument represents an XML document which contains the root level XML constructs, such as document type declaration (XDocumentType), root element (XElement), and comments objects (XComment).
To load and query XML document using LINQ, follow these steps:
1. Include the following namespaces on your project.
using System.Linq;
using System.Xml.Linq;
2. To load the XML document use XDocument class.
XDocument xml = XDocument.Load(@"EmployeeSample.xml");
3. Now you can parse through the loaded XML using LINQ.
var query = from p in xml.Elements("employees").Elements("employee")
where (int)p.Element("id") == 1
select p;
4. To confirm the content of the query, display it on the console.
foreach (var record in query)
{
Console.WriteLine("Employee: {0} {1}",
record.Element("firstname").Value,
record.Element("lastname").Value);
}
The complete source code to load and query xml document using LINQ:
static void Main(string[] args)
{
XDocument xml = XDocument.Load(@"EmployeeSample.xml");
var query = from p in xml.Elements("employees").Elements("employee")
where (int)p.Element("id") == 1
select p;
foreach (var record in query)
{
Console.WriteLine("Employee: {0} {1}",
record.Element("firstname").Value,
record.Element("lastname").Value);
}
}
For more LINQ coding tips, subscribe now
3 comments:
Very Good! This really helped me a lot. I was able to get to the information I needed and develop the solution sooner.
Thank you
thanks for code
Font makes your post tough to read
Most helpful LINQ post I"ve seen, imh. Thanks!
Post a Comment