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&g开发者_高级运维t;
</Student>
In the above XML I want to change the value of Student name "test" to something else like "Undertest".
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
you can try something like
xElement.SetAttributeValue
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
精彩评论