string xmlString = ""; XElement person = XElement.Parse(xmlString); string ageValue; if (person.TryAttribute("age", out ageValue)) { Console.WriteLine("Age is {0}", ageValue); } else { Console.WriteLine("Age attribute doesn't exist."); }
XElement person = new XElement("Person", new XAttribute("name", "John Doe")); string ageValue; if (person.TryAttribute("age", out ageValue)) { Console.WriteLine("Age is {0}", ageValue); } else { Console.WriteLine("Age attribute doesn't exist."); }In the above example, we create a Person element with only one attribute 'name' and no 'age' attribute. We try to get the value of the 'age' attribute using the TryAttribute method. Since the 'age' attribute doesn't exist, a message is displayed accordingly. The System.Xml.Linq namespace is included in the .NET Framework package.