MSDN

Microsoft Docs

XAttribute Class

Namespace: System.Xml.Linq

Assembly: System.Xml.Linq.dll

Summary

Represents an XML attribute. Provides methods for accessing and manipulating attribute values and for getting the attribute’s name, namespace, and parent element.

Syntax

public sealed class XAttribute : XObject

Constructors

SignatureDescription
XAttribute(XName name, object value)Initializes a new instance of the XAttribute class with the specified name and value.
XAttribute(XName name)Initializes a new instance of the XAttribute class with the specified name and an empty value.

Properties

PropertyTypeDescription
NameXNameGets the fully qualified name of the attribute.
ValuestringGets or sets the value of the attribute.
ParentXElementGets the element that contains this attribute.

Methods

MethodReturn TypeDescription
ToString()stringReturns the attribute as a formatted XML string.
Remove()voidRemoves this attribute from its parent element.

Example

// Create an XML element with attributes
XElement person = new XElement("Person",
    new XAttribute("id", 1),
    new XAttribute("name", "John Doe"),
    new XAttribute("age", 30));

// Output the XML
Console.WriteLine(person);

// Modify an attribute
person.Attribute("age").Value = "31";
Console.WriteLine("Updated age: " + person.Attribute("age").Value);

See Also