XElement element = XElement.Parse("The Catcher in the Rye "); string author = element.GetAttribute("author"); Console.WriteLine(author); // "John Smith"
XElement root = new XElement("bookstore", new XElement("book", new XAttribute("author", "John Smith"), new XAttribute("title", "The Catcher in the Rye"), new XElement("price", "$10.99") ) ); XElement book = root.Element("book"); string author = book.GetAttribute("author"); Console.WriteLine(author); // "John Smith"In this example, an XElement object is created manually with nested elements and attributes. The Element method is used to retrieve the "book" element, and then the GetAttribute method is used to retrieve the "author" attribute. The package library for this code is System.Xml.Linq, which is included in the .NET Framework.