XAttribute Class Overview
Attributes are name/value pairs that are associated with an element. The XAttribute class represents XML attributes.
Overview
Working with attributes in LINQ to XML is similar to working with elements. Their constructors are similar. The methods that you use to retrieve collections of them are similar. A LINQ query expression for a collection of attributes looks very similar to a LINQ query expression for a collection of elements.
The order in which attributes were added to an element is preserved. That is, when you iterate through the attributes, you see them in the same order that they were added.
The XAttribute Constructor
The following constructor of the XAttribute class is the one that you will most commonly use:
Constructor | Description |
---|---|
|
Creates an XAttribute object. The name argument specifies the name of the attribute; content specifies the content of the attribute. |
Creating an Element with an Attribute
The following code shows the common task of creating an element that contains an attribute:
XElement phone = new XElement("Phone",
new XAttribute("Type", "Home"),
"555-555-5555");
Console.WriteLine(phone);
With Visual Basic, you can use XML literals:
Dim phone As XElement = <Phone Type="Home">555-555-5555</Phone>
Console.WriteLine(phone)
This example produces the following output:
<Phone Type="Home">555-555-5555</Phone>
Functional Construction of Attributes
You can construct XAttribute objects in-line with the construction of XElement objects, as follows:
XElement c = new XElement("Customers",
new XElement("Customer",
new XElement("Name", "John Doe"),
new XElement("PhoneNumbers",
new XElement("Phone",
new XAttribute("type", "home"),
"555-555-5555"),
new XElement("Phone",
new XAttribute("type", "work"),
"666-666-6666")
)
)
);
Console.WriteLine(c);
Dim c As XElement = _
<Customers>
<Customer>
<Name>John Doe</Name>
<PhoneNumbers>
<Phone type="home">555-555-5555</Phone>
<Phone type="work">666-666-6666</Phone>
</PhoneNumbers>
</Customer>
</Customers>
Console.WriteLine(c)
This example produces the following output:
<Customers>
<Customer>
<Name>John Doe</Name>
<PhoneNumbers>
<Phone type="home">555-555-5555</Phone>
<Phone type="work">666-666-6666</Phone>
</PhoneNumbers>
</Customer>
</Customers>
Attributes Are Not Nodes
There are some differences between attributes and elements. XAttribute objects are not nodes in the XML tree. They are name/value pairs associated with an XML element. In contrast to the Document Object Model (DOM), this more closely reflects the structure of XML. Although XAttribute objects are not actually nodes in the XML tree, working with XAttribute objects is very similar to working with XElement objects.
This distinction is primarily important only to developers who are writing code that works with XML trees at the node level. Many developers will not be concerned with this distinction.