C# : Modify a xml node -
i have xml file :
<?xml version="1.0" encoding="utf-8"?> <reminders> <reminder> <title>alarm1</title> <description>desc1</description> <time>03/07/2012 10:11am</time> <snooze>1</snooze> <repeat>none</repeat> </reminder> </reminders>
and want modify innertext alarm1 value wrote code duplicate entire node .
xmldocument xml = new xmldocument(); xml.load("0.xml"); xmlnodelist elements = xml.selectnodes("//reminders"); foreach (xmlnode element in elements) { if (element.innertext == "alarm1") { xmlnode newvalue = xml.createelement("modified"); element.replacechild(newvalue, element); xml.save("0.xml"); } }
and tried code :
foreach (xmlelement element in xml.selectnodes("//reminder")) { if (element.innertext == "alarm1") { xmlnode newvalue = xml.createelement("modified"); element.replacechild(newvalue, element); xml.save("0.xml"); } }
but doesn`t work....
edit 1 : [figured out new code]
xmldocument xml = new xmldocument(); xml.load("0.xml"); foreach (xmlelement element in xml.selectnodes("//reminder")) { foreach (xmlelement element1 in element) { if (element.selectsinglenode("//title").innertext == "alarm1") { xmlnode newvalue = xml.createelement("modified"); element.replacechild(newvalue, element1); xml.save("0.xml"); } } }
but made alarm1 becomes
<modified />
edit 2 : [i solved :d] okay here code figure out :
xmldocument xml = new xmldocument(); xml.load("0.xml"); foreach (xmlelement element in xml.selectnodes("//reminder")) { foreach (xmlelement element1 in element) { if (element.selectsinglenode("//title").innertext == "alarm1") { messagebox.show(element1.innertext); xmlnode newvalue = xml.createelement("title"); newvalue.innertext = "modified"; element.replacechild(newvalue, element1); xml.save("0.xml"); } } }
i`ll appreciate helps , thanks.
try this:
xml.selectsinglenode("//reminder/title").innertext = "newvalue";
your foreach
line looping through list of elements called "reminders", not it's child nodes.
take @ xpath tutorial more information:
Comments
Post a Comment