Linq XML samples

by sunil ravulapalli /5. November 2010 15:39 /c# /Comments (0)

Sample XML:

  
    ChapterOne-SectionOne
    ChapterOne-SectionTwo
    ChapterOne-SectionThree
    ChapterOne-SectionFour
    ChapterOne-SectionFive
  
  
    ChapterTwo-SectionOne
    ChapterTwo-SectionTwo
    ChapterTwo-SectionThree
    ChapterTwo-SectionFour
    ChapterTwo-SectionFive
  
	

Lets say, I want to print out contents of Chapter 2-Section 4:

XElement data = 
XElement.Load(Request.PhysicalApplicationPath + "book.xml");

XElement chapterElement =
     (
        from chapter in data.Elements("chapter")
        where chapter.Attribute("id").Value == "2"
        select chapter
     ).Single();


XElement sectionElement =
     (
        from section in chapterElement.Elements("section")
        where section.Attribute("id").Value == "4"
        select section
     ).Single();

Response.Write(sectionElement .Value);

(I could complicate matters and write some embedded queries, but I chose to be more readable)

blog comments powered by Disqus