C# 如何使用LINQ更新XMl值和写回
我有一个关于使用Linq更新节点值的查询 例如,我必须更新C# 如何使用LINQ更新XMl值和写回,c#,linq,.net-3.5,C#,Linq,.net 3.5,我有一个关于使用Linq更新节点值的查询 例如,我必须更新 <Student> <studentdetail> <studentname>test</studentname> <libraryid>hem001</libraryid> </studentdetail> </Student> 测试 hem001 在上面的XML中,我想将学生名“test”的值改为“Under
<Student>
<studentdetail>
<studentname>test</studentname>
<libraryid>hem001</libraryid>
</studentdetail>
</Student>
测试
hem001
在上面的XML中,我想将学生名“test”的值改为“Undertest”之类的值
这段代码是做你想做的事情的一种非常基本的方法
//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");
进一步阅读:
我主要使用SingleOrDefault() 我相信alexjamesbrown应该写SetElementValue而不是SetAttributeValue 您也可以这样做: SingleOrDefault()。值==“替换字符串”
致以最诚挚的问候XML test hem001我在一个XML中有多个sunch东西,我想通过搜索特定元素和唯一的更新来更新,是的,我需要加载只是一个示例的XML一旦你有了XDocument,你可以在它上使用linq-从xmlDocument中的n开始
using System.Linq;
using System.Xml.Linq;