Parse xml – Linq to Xml

How to parse xml?

It’s very simple. Linq offers us an extension specifically for this task – Linq to XML.

Let’s assume that we have to parse XML which is presented below.

We have to attach using System.Xml.Linq.

Let’s try get information about all authors in our xml.

Explain for 7th line – “Take me all nodes which is called ‘book’.” and next we iterate on this collection(8th line).  At the end we display all authors of books.

Operator “?.Value” means the same like this – item.Element(“author”)==null?null:item.Element(“author”).Value. And that mean if item.Element(“author”) is null return null else return value from this.

But if this is linq we can use all the benefits offered that library.

linq to xml example

In this case we display all book’s title from filter collection where author is Corets, Eva.


On this example i showed you how linq is easy and powerfull library. Now let’s enjoy “easy” parsing XML. 😉

Link to project – here

One Comment on “Parse xml – Linq to Xml”

  1. Można byłoby opisać jak dostać się do pól i atrybutów XMLa w bardziej złożonych strukturach.

Leave a Reply

Your email address will not be published. Required fields are marked *