Mega Code Archive

 
Categories / C# / XML LINQ
 

It is easier to use casting when the attribute might or might not exist

using System; using System.Linq; using System.Xml; using System.Xml.Linq; using System.Collections; using System.Collections.Generic; public class MainClass{    public static void Main(){         XElement root = new XElement("Root",             new XAttribute("Att1", "attribute 1 content"),             new XAttribute("Att2", "2")         );         string c1 = (string)root.Attribute("Att1");         Console.WriteLine("c1:{0}", c1 == null ? "attribute does not exist" : c1);              } }