Click here to Skip to main content
15,879,326 members
Articles / Programming Languages / C#
Tip/Trick

Reading XML documents using LINQ

Rate me:
Please Sign up or sign in to vote.
4.92/5 (12 votes)
15 Jan 2011CPOL 50K   22   6
Reading XML documents using LINQ
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
<?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.

C#
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)


Written By
Software Developer (Senior) Dell
India India
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:

Comments and Discussions

 
GeneralReason for my vote of 5 Just what I needed. Pin
[Schnell]Konig18-Dec-11 12:26
[Schnell]Konig18-Dec-11 12:26 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.