O'Reilly logo

LINQ Pocket Reference by Joseph Albahari, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Working with Values

XElement and XAttribute both have a Value property of type string. If an element has a single XText child node, XElement’s Value property acts as a convenient shortcut to the content of that node. With XAttribute, the Value property is simply the attribute’s value.

Despite the storage differences, the X-DOM provides a consistent set of operations for working with element and attribute values.

Setting Values

There are two ways to assign a value: call SetValue or assign the Value property. SetValue is more flexible because it accepts not just strings, but other simple data types too:

	var e = new XElement ("date", DateTime.Now);
	e.SetValue (DateTime.Now.AddDays(1));
	Console.Write (e.Value);

	// RESULT: 2007-12-19T16:39:10.734375+09:00

We could have instead just set the element’s Value property, but this would mean manually converting the DateTime to a string. This is more complicated than calling ToString —it requires the use of XmlConvert for an XML-compliant result.

When you pass a value into XElement or XAttribute’s constructor, the same automatic conversion takes place for non-string types. This ensures that DateTimes is correctly formatted; true is written in lowercase, and double. NegativeInfinity is written as “-INF.”

Getting Values

To go the other way around and parse a Value back to a base type, you simply cast the XElement or XAttribute to the desired type. It sounds like it shouldn’t work— but it does! For instance:

 XElement e = new XElement ("now", DateTime.Now); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required