Click here to Skip to main content
Click here to Skip to main content

Reading XML documents using LINQ

By , 15 Jan 2011
 
LINQ simplifies working with XML data & you need not use Xpath or XQuery for reading XML. This tip is about querying XML using LINQ.
<?xml version="1.0" encoding="utf-8" ?>
<Books>
  <Book>
    <Subject>
      Social Science
    </Subject>
    <Content>
      History,Geography
    </Content>
  </Book>
 
  <Book>
    <Subject>
     General Science
    </Subject>
    <Content>
      Biology,Chemistry,Physics
    </Content>
  </Book>
  </Books>
This queries the XML & populates the listbox with values of Subject.
 
var books = from nodes in System.Xml.Linq.XElement.Load("Books.xml").Elements("Book") select nodes;
 
            if (books != null)
            {
                foreach (var b in books)
                {
                    listBox1.Items.Add(b.Element("Subject").Value.Trim());
 
                }
            }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Anupama Roy
Software Developer (Senior) Dell
India India
Member
I am a .Net developer working on C#,Asp.net,WCF,WF etc.I would like to utilize this space to share whatever I have come across so far working in .Net so that you can also learn & explore.
 
I hope you find these posts useful.I’d love to hear from you,so please post in your comments/feedback.
 
Visit my blog http://dotnetforyou.wordpress.com/ for more technical articles:

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Question?......really?membertrooper081417 Jan '11 - 3:34 
Confused | :confused:

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 16 Jan 2011
Article Copyright 2011 by Anupama Roy
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid