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

Get LINQ Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.