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 16.19

Print

Comments on this entry:

# re: Snippet per la lettura di un attributo XML

Left by Davide Mauri at 06/11/2006 16.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 17.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 17.50
Gravatar
:-)

# re: Snippet per la lettura di un attributo XML

Left by sohbet at 08/02/2009 14.01
Gravatar

# re: Snippet per la lettura di un attributo XML

Left by sohbet at 12/07/2009 19.58
Gravatar

# re: Snippet per la lettura di un attributo XML

Left by sohbet yap at 12/07/2009 19.58
Gravatar

Your comment:



 (will not be displayed)


 
 
 
Please add 5 and 5 and type the answer here:
 

Live Comment Preview:

 
«febbraio»
domlunmarmergiovensab
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910