Snippet per la lettura di un attributo XML

Molte volte è necessario leggere un file XML in modo programmatico, mappando ad esempio attributi di un nodo xml in campi del proprio object model. Questo snippet di codice permette di leggere un attributo di un nodo, convertirlo nel tipo desiderato e nel caso in cui l'attributo non esista o il relativo valore sia non convertibile nel tipo di destinazione, utilizzare un valore di default.

class XmlHelpers{ public static T GetAttribute<T>(XmlNode node ,string attributeName ,T defaultValue ){ T rtn = defaultValue; XmlAttribute attr = node.Attributes[attributeName]; if (attr != null) { Type type = typeof(T); if (type == typeof(string)) return (T)((object)attr.InnerText); TypeConverter converter = TypeDescriptor.GetConverter(type); try{ object result = converter.ConvertFromString(attr.InnerText); if (result is T) rtn = (T)result; }catch (System.FormatException){} } return rtn; } }

Per richiamarlo posso scrivere ad esempio:

Foo f = new Foo(); f.PropA = XmlHelpers.GetAttribute<bool>(fooNode, "A", false);
«novembre»
domlunmarmergiovensab
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789