Xelement. the setelementvalue method is very considerate. It will automatically determine whether the element has the child element. If there is an update or an addition, it will be deleted. It is also easy to laugh, xelement. setelementvalue ("lastname", null), which deletes the lastname element.
// We will use this to store a reference to one of the elements in the XML tree. <br/> xelement firstparticipant ipant; </P> <p> xdocument = new xdocument (<br/> New xelement ("bookparticipant ipants ", firstparticipant ipant = <br/> New xelement ("bookparticipant ipant", <br/> New xattribute ("type", "author"), <br/> New xelement ("firstname ", "Joe"), <br/> New xelement ("lastname", "rattz"); </P> <p> console. writeline (system. environment. newline + "before updating elements:"); <br/> console. writeline (xdocument); </P> <p> // first, we will use xelement. setelementvalue to update the value of an element. <br/> // since an element named firstname is there, its value will be updated to Joseph. <br/> firstparticipant ipant. setelementvalue ("firstname", "Joseph"); </P> <p> // second, we will use xelement. setelementvalue to add an element. <br/> // since no element named middleinitial exists, one will be added. <br/> firstparticipant ipant. setelementvalue ("middleinitial", "C"); </P> <p> // Third, we will use xelement. setelementvalue to remove an element. <br/> // setting an element's value to null will remove it. <br/> firstparticipant ipant. setelementvalue ("lastname", null); </P> <p> console. writeline (system. environment. newline + "after updating elements:"); <br/> console. writeline (xdocument );
Output
Before updating elements: <br/> <bookparticipant ipants> <br/> <bookparticipant ipant type = "author"> <br/> <firstname> Joe </firstname> <br/> <lastname> rattz </lastname> <br/> </bookparticipant ipant> <br/> </bookparticipant ipants> </P> <p> after updating elements: <br/> <bookparticipant ipants> <br/> <bookparticipant ipant type = "author"> <br/> <firstname> Joseph </firstname> <br/> <middleinitial> C </middleinitial> <br/> </bookparticipant ipant> <br/> </bookparticipant ipants>
The author also raised a warning for this method.
Just because calling the setelementvalue method with a value of null removes the node, don't
Make the mistake of thinking that manually setting an element's value to NULL is the same as removing it in
LINQ to xml api. This is merely the behavior of the setelementvalue method. If you attempt to set an element's
Value to null using its value property, an exception will be thrown.
Do not naively thinkSetelementvalueIf an element is set to null, you can delete the node by setting the value of an element to null.
If you try to set the value of that element to null, an exception will be thrown.