tags:

views:

23

answers:

2

I have a query about updating a node value using Linq,

For example I have to update

<Student>
  <studentdetail>
    <studentname>test</studentname>
    <libraryid>hem001</libraryid>
  </studentdetail>
</Student>

In the above XML I want to change the value of Student name "test" to something else like "Undertest".

A: 

you can try something like

xElement.SetAttributeValue

anishmarokey
+1  A: 

This code is a very basic way of doing what you want.

        //there are obviously better ways of "loading" the xml
        var xmlDocument = XDocument.Parse("<Student> <studentdetail> <studentname>test</studentname> <libraryid>hem001</libraryid> </studentdetail></Student>");

        //this will only work IF the studentname node exists (the .Single() blows up if it's not there)
        xmlDocument.Descendants("studentname").Single().SetAttributeValue("studentname", "Undertest");

You will need the following references:

using System.Linq;
using System.Xml.Linq;

Futher reading: http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx

alex
I am having multiple sunch thing in one XML i want to update by searching certain element and the only update, yes i need to load the XML that was just an example
NewDev
once you have the XDocument, you can use linq on it - from n in xmlDocument.Descendants where n.Name=="studentname" for example
alex