Efficient Way to Parse XML

deandazzle

New Member
I find it puzzling to determine the best way to parse some XML. It seems they are so many possible ways and none have really clicked with me.My current attempt looks something like this:\[code\]XElement xelement = XElement.Parse(xmlText);var name = xelement.Element("Employee").Attribute("name").Value;\[/code\]So, this works. But it throws an exception if either the "Employee" element or the "name" attribute is missing. I don't want to throw an exception.Exploring some examples available online, I see code like this:\[code\]XElement xelement = XElement.Load("..\\..\\Employees.xml");IEnumerable<XElement> employees = xelement.Elements();Console.WriteLine("List of all Employee Names :");foreach (var employee in employees){ Console.WriteLine(employee.Element("Name").Value);}\[/code\]This would seem to suffer from the exact same issue. If the "Name" element does not exist, \[code\]Element()\[/code\] returns \[code\]null\[/code\] and there is an error calling the \[code\]Value\[/code\] property.I need a number of blocks like the first code snippet above. Is there a simple way to have it work and not throw an exception if some data is missing?
 
Back
Top