CSharp - LINQ XML Attributes

Introduction

The Attributes operator can be called on a sequence of elements and returns a sequence containing the attributes of each source element.

Prototypes

The Attributes operator has two prototypes. The First Attributes Prototype

public static IEnumerable<XAttribute> Attributes (
        this IEnumerable<XElement> source
)

This version of the operator can be called on a sequence of elements and returns a sequence of attributes containing all the attributes for each source element.

The Second Attributes Prototype

public static IEnumerable<XAttribute> Attributes (
        this IEnumerable<XElement> source,
        XName name
)

This version of the operator returns attributes by the specified name.

Demo

using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

class Program/*from   w  w w .  j  av  a  2 s .  c  o  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.Element("Books").Elements("Book");
        
              //  First, we will display the source elements.
        foreach (XElement element in elements)
        {
          Console.WriteLine("Source element: {0} : value = {1}",
            element.Name, element.Value);
        }
        
        //  Now, we will display each source element's attributes.
        foreach (XAttribute attribute in elements.Attributes())
        {
          Console.WriteLine("Attribute: {0} : value = {1}",
            attribute.Name, attribute.Value);
        }
    }
}

Result

Related Topics