XElement.Attribute Method (System.Xml.Linq)

Switch View :
ScriptFree
.NET Framework Class Library
XElement.Attribute Method

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

Namespace:  System.Xml.Linq
Assembly:  System.Xml.Linq (in System.Xml.Linq.dll)
Syntax

Visual Basic
Public Function Attribute ( _
	name As XName _
) As XAttribute
C#
public XAttribute Attribute(
	XName name
)
Visual C++
public:
XAttribute^ Attribute(
	XName^ name
)
F#
member Attribute : 
        name:XName -> XAttribute 

Parameters

name
Type: System.Xml.Linq.XName
The XName of the XAttribute to get.

Return Value

Type: System.Xml.Linq.XAttribute
An XAttribute that has the specified XName; null if there is no attribute with the specified name.
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.

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);
Visual Basic
Dim xmlTree As XElement = <Root Att="attribute content"/>

Dim att As XAttribute = 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 Working 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);
Visual Basic
Imports <xmlns:aw="http://www.adventure-works.com">

Module Module1
    Sub Main()
        Dim xmlTree As XElement = <aw:Root aw:Att="attribute content"/>

        Dim att As XAttribute = xmlTree.Attribute(GetXmlNamespace(aw) + "Att")
        Console.WriteLine(att)
    End Sub
End Module

This example produces the following output:

aw:Att="attribute content"
Version Information

.NET Framework

Supported in: 4, 3.5

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
See Also

Reference

Other Resources