We recommend using Visual Studio 2017
This documentation is archived and is not being maintained.

How to: Retrieve the Value of an Attribute (LINQ to XML)

This topic shows how to obtain the value of attributes. There are two main ways: You can cast an XAttribute to the desired type; the explicit conversion operator then converts the contents of the element or attribute to the specified type. Alternatively, you can use the Value property. However, casting is generally the better approach. If you cast the attribute to a nullable type, the code is simpler to write when retrieving the value of an attribute that might or might not exist. For examples of this technique, see How to: Retrieve the Value of an Element (LINQ to XML).

To retrieve the value of an attribute, you just cast the XAttribute object to your desired type.

In Visual Basic, you can use the integrated attribute property to retrieve the value of an attribute.

XElement root = new XElement("Root",
                    new XAttribute("Attr", "abcde")
                );
Console.WriteLine(root);
string str = (string)root.Attribute("Attr");
Console.WriteLine(str);

This example produces the following output:

<Root Attr="abcde" />
abcde

In Visual Basic, you can use the integrated attribute property to set the value of an attribute. Further, if you use the integrated attribute property to set the value of an attribute that does not exist, the attribute will be created.

Dim root As XElement = <Root Att1="content"/>
root.@Att1 = "new content"
root.@Att2 = "new attribute"
Console.WriteLine(root)

This example produces the following output:

<Root Att1="new content" Att2="new attribute" />

The following example shows how to retrieve the value of an attribute where the attribute is in a namespace. For more information, see Working with XML Namespaces.

XNamespace aw = "http://www.adventure-works.com";
XElement root = new XElement(aw + "Root",
                    new XAttribute(aw + "Attr", "abcde")
                );
string str = (string)root.Attribute(aw + "Attr");
Console.WriteLine(str);

This example produces the following output:

abcde
Show: