Tuesday, March 29, 2011

How to get nested tags using Linq To XML query

Let's say we have the next XML:


This is a link example


  
    
      
        Text...
        Text...
        text...
        Text...
        Text...
      
      
        Text
        Text
        Text
      
      
        Info
        Info
        Info
        Info
      
    
  


And you want to get the tags inside on the chapter number two.
You can use this code:
// Load the document
XDocument loadedData = XDocument.Load("kjv.xml");

// Get the testament
IEnumerable<xelement> xmlTestament = loadedData.Descendants("testament").Where(c => ((string)c.Attribute("name")).Equals("New"));

// Get the book
IEnumerable<xelement> xmlBook      = xmlTestament.Descendants("book").Where(c => ((string)c.Attribute("name")).Equals("Matthew"));

// Get the chapter
IEnumerable<xelement> xmlChapter = xmlBook.Descendants("chapter").Where(c => ((string)c.Attribute("number")).Equals("2"));

foreach (string s in xmlChapter.Descendants("verse"))
{
  listBox1.Items.Add(s);
}

// -----------------------------------------------------------------------------------------


This is another way to get the info needed
//
// Load the document
XDocument loadedData = XDocument.Load("kjv.xml");

// Get the info
IEnumerable<XElement> data1 = from query in loadedData.Descendants("testament")
                                             where (string)query.Attribute("name").Value == "New"
                                        from book in loadedData.Descendants("book")
                                             where (string)book.Attribute("name").Value == "Matthew"
                                        from chap in loadedData.Descendants("chapter")
                                             where (string)chap.Attribute("number").Value == "2"
                                        select chap;

foreach (string s in data1.Descendants("verse"))
{
   listBox1.Items.Add(s);
}


//-----------------------------------------------------------------------------------


No comments:

Post a Comment