65.9K
CodeProject is changing. Read more.
Home

Reading XML documents using LINQ

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.92/5 (12 votes)

Jan 14, 2011

CPOL
viewsIcon

51389

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

                }
            }