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

Tagged as

Reading XML documents using LINQ

, 15 Jan 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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 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)

Share

About the Author

Anupama Roy
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

 
QuestionMinh Pinmemberhoangminh1235-Aug-13 22:31 
GeneralMy vote of 4 PinmemberMember 1011024015-Jun-13 13:00 
GeneralReason for my vote of 5 just the biscuit thanks for the tip! PinmemberErik Rude22-Feb-12 22:51 
GeneralReason for my vote of 5 Just what I needed. Pinmember[Schnell]Konig18-Dec-11 12:26 
GeneralIn most cases, a query expression of "from x in source selec... PinmemberRichard Deeming18-Jan-11 9:19 
In most cases, a query expression of "from x in source select x" can be replaced with "source"; the extra call to "Select" doesn't add anything here.
 
Also, your example would fail if one of the Book elements didn't have a Subject element, since b.Element("Subject") would return null.
Question?......really? Pinmembertrooper081417-Jan-11 3:34 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.141015.1 | Last Updated 16 Jan 2011
Article Copyright 2011 by Anupama Roy
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid