C# : Modify a xml node

孤街醉人 提交于 2019-11-29 06:05:56

Try this:

xml.SelectSingleNode("//reminder/Title").InnerText = "NewValue";

Your foreach line is simply looping through a list of elements called "reminders", not it's child nodes.

Take a look at this xpath tutorial for more information:

http://www.w3schools.com/xpath/xpath_intro.asp

If you want to use linq with xml (I find it the best way) then you will want to use the System.Xml.Linq namespace. The classes in that namespace are all prefixed with just X not Xml. The functionality in this namespace is newer, better and much easier to manipulate with Linq.

var xml = XDocument.Load("0.xml");
var alarm1 = xml.Descendants("reminder")
                .Single(r => r.Element("Title") == "Alarm1");

This code will give you a variable, alarm1 that is the reminder that has a title node of "Alarm1."

From that point its not clear to me exactly what you want to modify. If you just want to change the title then ...

alarm1.Element("Title").Value = "MODIFIED";
xml.Save("0.xml");
XDocument doc = XDocument.Load("0.xml");
IEnumerable<XElement> rech =
                     from el in doc.Root.Elements("reminder")
                     where (string)el.Element("Title") == "Alarm1"
                     select el;
if (rech.Count() != 0)
{
   foreach (XElement el in rech)
   {
       el.Element("Title").SetValue("NEW TITLE");
   }
}
doc.Save("0.xml");
XDocument xDoc = XDocument.Load(.....);
xDoc.Descendants("Title").First().Value = "New Value";
xDoc.Save(...)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!