XElement.Attribute(XName) Method

Definition

Returns the XAttribute of this XElement that has the specified XName.

C#
public System.Xml.Linq.XAttribute Attribute(System.Xml.Linq.XName name);
C#
public System.Xml.Linq.XAttribute? Attribute(System.Xml.Linq.XName name);

Parameters

name
XName

The XName of the XAttribute to get.

Returns

An XAttribute that has the specified XName; null if there is no attribute with the specified name.

Examples

The following example creates an element with an attribute. It then retrieves the attribute using this method.

C#
XElement xmlTree = new XElement("Root",
    new XAttribute("Att", "attribute content")
);
XAttribute att = xmlTree.Attribute("Att");
Console.WriteLine(att);

This example produces the following output:

Att="attribute content"

The following is the same example, but in this case the XML is in a namespace. For more information, see Work with XML Namespaces.

C#
XNamespace aw = "http://www.adventure-works.com";
XElement xmlTree = new XElement(aw + "Root",
    new XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com"),
    new XAttribute(aw + "Att", "attribute content")
);
XAttribute att = xmlTree.Attribute(aw + "Att");
Console.WriteLine(att);

This example produces the following output:

aw:Att="attribute content"

Remarks

Some axis methods return collections of elements or attributes. This method returns only a single attribute. Sometimes this is referred to as a singleton (in contrast to a collection).

Visual Basic users can use the integrated attribute axis to retrieve the value of an attribute with a specified name.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

See also