Export (0) Print
Expand All

XAttribute Constructor (XName, Object)

Initializes a new instance of the XAttribute class from the specified name and value.

Namespace:  System.Xml.Linq
Assemblies:   System.Xml.XDocument (in System.Xml.XDocument.dll)
  System.Xml.Linq (in System.Xml.Linq.dll)

public:
XAttribute(
	XName^ name, 
	Object^ value
)

Parameters

name
Type: System.Xml.Linq::XName

The XName of the attribute.

value
Type: System::Object

An Object containing the value of the attribute.

ExceptionCondition
ArgumentNullException

The name or value parameter is nullptr.

There is an implicit conversion from string to XName. Typical use of this constructor is to specify a string as the first parameter instead of creating a new XName, as follows:

XElement root = new XElement("Root",
    new XAttribute("AnAttributeName", "Content")
);

You can also use the addition operator overload with an XNamespace and a string to create an XName, as follows:

XNamespace aw = "http://www.adventure-works.com";
XElement root = new XElement(aw + "Root",
    new XAttribute(aw + "AnAttributeName", "Content")
);

For more information, see Working with XML Namespaces.

These same approaches will work for Visual Basic, however XML literals provide a better approach for creating XML trees.

The value parameter can be a String, double, float, decimal, bool, DateTime, or TimeSpan. If the value is a DateTime or TimeSpan, the value of the attribute is formatted correctly per the W3C specifications.

The following example uses this constructor to create attributes. It passes strings as the first argument to the XAttribute constructor, which are then implicitly converted to XName objects. The attributes are added to an element.

No code example is currently available or this language may not be supported.

This example produces the following output:

<Root Att1="Some text" Att2="12.345" Att3="2006-10-06T12:30:00" Att4="1" Att5="2" Att6="3" />

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

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

Show:
© 2014 Microsoft