58BITS
  • Home
  • Tech Stuff
  • Other Stuff
  • Photos
  • About
  • Contact
58BITS
  • Home
  • Tech Stuff
  • Get XElement Value with Default

Get XElement Value with Default

Submitted on Aug 01, 2009, 6:24 p.m.

Thanks to this post at .Net Dojo , here’s a utility method for getting a safe value from an XElement, returning a default value if the element was not found.

public static T GetElementValue<T>(XElement parent, string elementId, T defaultValue) where T : IConvertible
{
XElement element = parent.Element(elementId);
if (element != null)
return (T)Convert.ChangeType(element.Value, typeof(T), CultureInfo.InvariantCulture);
else
return defaultValue;
}

I’ve been using this combined with .Net 3.0 object initializers to re-hydrate objects from Xml with safe values, like…

var myClass = new MyClass()
{
Name = GetElementValue(parent, "Name", String.Empty),
IsDefault = GetElementValue(parent, "IsDefault ", true),
YearsLeft = GetElementValue(parent, "Yearsleft", 100)
}

Featured

ความเสี่ยงที่เกี่ยวข้องกับเทคโนโลยีหน้าจอสำหรับเด็ก (วัยก่อนรุ่นและวัยรุ่น)

ความเสี่ยงที่เกี่ยวข้องกับเทคโนโลยีหน้าจอสำหรับเด็ก (วัยก่อนรุ่นและวัยรุ่น)

Sep 15, 2024, 10:53 a.m.
An Executive Summary of the Current State of AI

An Executive Summary of the Current State of AI

Jul 20, 2024, 5:45 p.m.
Digital Media Preservation - Why Media Organizations Can’t Archive

Digital Media Preservation - Why Media Organizations Can’t Archive

Sep 17, 2012, 11:59 a.m.
The Long Road Home

The Long Road Home

Nov 09, 2011, 8:12 p.m.

Latest

อันตรายที่ซ่อนเร้นของน้ำตาล: ผลกระทบต่อสมองเด็กและสุขภาพผู้ใหญ่

Nov 27, 2024, 2:36 a.m.

General Purpose Encrypt and Decrypt Functions with Jose

Sep 16, 2024, 11:19 p.m.

ความเสี่ยงที่เกี่ยวข้องกับเทคโนโลยีหน้าจอสำหรับเด็ก (วัยก่อนรุ่นและวัยรุ่น)

Sep 15, 2024, 10:53 a.m.

Migrating a Google Workspace Account to a Personal Google Gmail Account

Aug 04, 2024, 9:30 p.m.
58bits

Tech, art, and life...

Copyright © 2026 Anthony Bouch. All rights reserved.

Made with ❤️ by Infonomic

Explore
  • Home
  • Tech Stuff
  • Other Stuff
  • Photos
Legal
  • Terms of Use
  • Privacy Policy
  • Cookies
Connect
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Copyright © 2026 Anthony Bouch. All rights reserved.

Made with ❤️ by Infonomic

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.