CSharp - Obtaining Elements Without Reaching

Introduction

In the following example, we obtain every descendant element in the document named Book.

Demo

using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Xml.Xsl;

class Program/*from  ww  w .  ja  va2  s  .co  m*/
{
    static void Main(string[] args){
      XDocument xDocument = new XDocument(
        new XElement("Books",
          new XElement("Book",
            new XAttribute("type", "Author"),
            new XElement("FirstName", "Joe"),
            new XElement("LastName", "Ruby")),
          new XElement("Book",
            new XAttribute("type", "Editor"),
            new XElement("FirstName", "PHP"),
            new XElement("LastName", "Python"))));

      IEnumerable<XElement> elements = xDocument.Descendants("Book");

      foreach (XElement element in elements)
      {
        Console.WriteLine("Element: {0} : value = {1}",
          element.Name, element.Value);
      }
    }
}

Result

Related Topic