Quickly Changing Values of XML Elements Using LINQ

Avatar

Beth

I’ve had many questions lately on how you can query for a specific node in an XML document (or fragment) and change it’s value using LINQ. (This must mean that people are really starting to use this stuff so I’m pretty excited.) This is really easy to do because you can modify the values of the selected XElements from your queries and that will change the source XML.


Here’s an example:


Couple things to note above, remember to import any namespaces being used in the XML otherwise your query will yield no results. And remember you can get XML IntelliSense if you import a schema (this is really easy, watch this). Of course, you can load the XML from a file (or URI) instead of using a literal and and get the same results.


In this example we’re overwriting the source document, plants.xml, with our new values. Both examples produce this resulting XML:

Enjoy!

Avatar
Beth Massi

Follow Beth   

0 comments

Comments are closed.