XElement Class Overview
The XElement class is one of the fundamental classes in LINQ to XML. It represents an XML element. You can use this class to create elements; change the content of the element; add, change, or delete child elements; add attributes to an element; or serialize the contents of an element in text form. You can also interoperate with other classes in System.Xml, such as XmlReader, XmlWriter, and XslCompiledTransform.
This topic describes the functionality provided by the XElement class.
You can construct XML trees in a variety of ways, including the following:
You can construct an XML tree in code. For more information, see Creating XML Trees.
If you have a module that can write content to an XmlWriter, you can use the CreateWriter method to create a writer, pass the writer to the module, and then use the content that is written to the XmlWriter to populate the XML tree.
However, the most common way to create an XML tree is as follows:
Dim contacts As XElement = _ <Contacts> <Contact> <Name>Patrick Hines</Name> <Phone>206-555-0144</Phone> <Address> <Street1>123 Main St</Street1> <City>Mercer Island</City> <State>WA</State> <Postal>68042</Postal> </Address> </Contact> </Contacts>
Another very common technique for creating an XML tree involves using the results of a LINQ query to populate an XML tree, as shown in the following example:
Dim srcTree As XElement = _ <Root> <Element>1</Element> <Element>2</Element> <Element>3</Element> <Element>4</Element> <Element>5</Element> </Root> Dim xmlTree As XElement = _ <Root> <Child>1</Child> <Child>2</Child> <%= From el In srcTree.Elements() _ Where el.Value > 2 _ Select el %> </Root> Console.WriteLine(xmlTree)
This example produces the following output:
You can use axis methods to retrieve attributes, child elements, descendant elements, and ancestor elements. LINQ queries operate on axis methods, and provide several flexible and powerful ways to navigate through and process an XML tree.
For more information, see LINQ to XML Axes.
You can write LINQ queries that extract data from an XML tree.
For more information, see Querying XML Trees.