CSharp examples for System.Xml:XML Attribute
Gets the value of the given XML attribute as a DateTime.
// Permission is hereby granted, free of charge, to any person obtaining using System.Xml; using System.Globalization; using System.Collections.Generic; using System;/* w w w .j a v a 2s . c om*/ public class Main{ /// <summary> /// Gets the value of the given attribute as a DateTime. /// </summary> /// <param name="result">The result.</param> /// <param name="name">The name.</param> /// <param name="defaultValue">The default value.</param> /// <returns></returns> public static DateTime GetAttribute(this XmlNode result, string name, DateTime defaultValue) { string dateStr = GetAttribute(result, name); if (dateStr == null) return defaultValue; DateTime date; if (!DateTime.TryParse(dateStr, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AllowWhiteSpaces, out date)) return defaultValue; return date; } /// <summary> /// Gets the value of the given attribute as a double. /// </summary> /// <param name="result">The result.</param> /// <param name="name">The name.</param> /// <param name="defaultValue">The default value.</param> /// <returns></returns> public static double GetAttribute(this XmlNode result, string name, double defaultValue) { XmlAttribute attr = result.Attributes[name]; return attr == null ? defaultValue : double.Parse(attr.Value, System.Globalization.CultureInfo.InvariantCulture); } /// <summary> /// Gets the value of the given attribute as an int. /// </summary> /// <param name="result">The result.</param> /// <param name="name">The name.</param> /// <param name="defaultValue">The default value.</param> /// <returns></returns> public static int GetAttribute(this XmlNode result, string name, int defaultValue) { XmlAttribute attr = result.Attributes[name]; return attr == null ? defaultValue : int.Parse(attr.Value, System.Globalization.CultureInfo.InvariantCulture); } #region Safe Attribute Access /// <summary> /// Gets the value of the given attribute. /// </summary> /// <param name="result">The result.</param> /// <param name="name">The name.</param> /// <returns></returns> public static string GetAttribute(this XmlNode result, string name) { XmlAttribute attr = result.Attributes[name]; return attr == null ? null : attr.Value; } }