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);

posted @ lunedì 6 novembre 2006 18:19

Print

Comments on this entry:

# re: Snippet per la lettura di un attributo XML

Left by Davide Mauri at 06/11/2006 18:58
Gravatar
Usare "catch (Exception){}" non è consigliabile. E' molto meglio intercettare le eccezioni "previste" e lasciare quelle impreviste al loro destino. Se ci fosse una "OutOfMemoryException" il codice in questione nasconderebbe l'errore....

# re: Snippet per la lettura di un attributo XML

Left by Cristian Bressan at 06/11/2006 19:07
Gravatar
Errata Corrige su segnalazione di Davide.

# re: Snippet per la lettura di un attributo XML

Left by Davide Mauri at 06/11/2006 19:50
Gravatar
:-)

# re: Snippet per la lettura di un attributo XML

Left by sohbet at 08/02/2009 16:01
Gravatar

# re: Snippet per la lettura di un attributo XML

Left by wen at 30/10/2014 18:19
Gravatar
perspective economy months system information check credit score banking director consumers
Comments have been closed on this topic.
«aprile»
domlunmarmergiovensab
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011