Reading XML documents using LINQ

Posted: January 14, 2011 in LINQ
Tags: , , , ,

Did you know that LINQ simplifies working with XML data & you need not use Xpath or XQuery for reading XML?Below code queries the xml & populates the listbox with values of Subject node under Book.

<?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>

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());

}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s