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
| Signature | Description |
|---|---|
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
| Property | Type | Description |
|---|---|---|
Name | XName | Gets the fully qualified name of the attribute. |
Value | string | Gets or sets the value of the attribute. |
Parent | XElement | Gets the element that contains this attribute. |
Methods
| Method | Return Type | Description |
|---|---|---|
ToString() | string | Returns the attribute as a formatted XML string. |
Remove() | void | Removes 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);