NewDev
NewDev

Reputation: 21

how to Update the XMl value and write back using LINQ

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".

Upvotes: 0

Views: 184

Answers (3)

Blaz Brencic
Blaz Brencic

Reputation: 674

I mainly use SingleOrDefault().

And I believe alexjamesbrown you should wrote SetElementValue not SetAttributeValue.

Also you can do it like this: SingleOrDefault().Value == "replacement string".

Best regards

Upvotes: 0

Alex
Alex

Reputation: 38519

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

Upvotes: 1

anishMarokey
anishMarokey

Reputation: 11397

you can try something like

xElement.SetAttributeValue

Upvotes: 0

Related Questions