Posts Tagged ‘Reading XML documents using LINQ’

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

}
}