Updating an X-DOM

You can update elements and attributes in the following ways:

  • Call SetValue or reassign the Value property.

  • Call SetElementValue or SetAttributeValue.

  • Call one of the RemoveXXX methods.

  • Call one the of the AddXXX or ReplaceXXX methods, specifying fresh content.

You can also reassign the Name property on XElement objects.

Simple Value Updates

Members

Works on

SetValue (object)

XElement, XAttribute

Value

XElement, XAttribute

The SetValue method replaces an element or attribute’s content with a simple value. Setting the Value property does the same, but accepts string data only. We describe both of these functions in detail later (see the upcoming “Working with Values” section).

An effect of calling SetValue (or reassigning Value ) is that it replaces all child nodes:

	XElement settings = new XElement ("settings",
	                      new XElement ("timeout", 30)
	                    );
	settings.SetValue ("blah");
	Console.WriteLine (settings.ToString( ));

	// RESULT: <settings>blah</settings>

Updating Child Nodes and Attributes

Category

Members

Works on

Add

Add (params object[])

XContainer

 

AddFirst (params object[])

XContainer

Remove

RemoveNodes()

XContainer

 

RemoveAttributes()

XElement

 

RemoveAll()

XElement

Update

ReplaceNodes (params object[])

XContainer

 

ReplaceAttributes (params object[])

XElement

 

ReplaceAll (params object[])

XElement

 

SetElementValue (XName, object)

XElement

 

SetAttributeValue (XName, object)

XElement

The most convenient methods in this group are the last two: SetElementValue ...

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.