c# - How to Update XML File in Windows Form -
i'm trying figure out how can go updating xml file. know how read , write, no idea how update existing record.
my xml file looks like:
<?xml version="1.0" standalone="yes"?> <categories> <category> <categoryid>1</categoryid> <categoryname>ayourvedic</categoryname> </category> <category> <categoryid>2</categoryid> <categoryname>daily needs</categoryname> </category> <category> <categoryid>3</categoryid> <categoryname>clothes</categoryname> </category> <category> <categoryid>4</categoryid> <categoryname>shops</categoryname> </category> <category> <categoryid>5</categoryid> <categoryname>daily use product</categoryname> </category> </categories>
and how i'm writing file:
private void btnupdate_click(object sender, eventargs e) { xmldocument xdoc = new xmldocument(); string path = "xmldata.xml"; xelement xelement; xelement = new xelement("category"); xelement element = new xelement( "category", new xattribute("categoryid", categoryid), new xattribute("categoryname", categoryname) ); xelement.add(element); xelement.save("path"); }
but code not working please 1 can give idea or solution.
using system.xml following code shall help:
static void main(string[] args) { string inputfile = @"d:\temp\cat.xml"; xmldocument xmldoc = new xmldocument(); xmldoc.load(inputfile); xmlnode root = xmldoc.documentelement; //method 1 xmlelement category = xmldoc.createelement("category"); xmlelement catid = xmldoc.createelement("categoryid"); xmlelement catname = xmldoc.createelement("categoryname"); catid.innertext = "6"; catname.innertext = "the newly added category"; category.appendchild(catid); category.appendchild(catname); root.appendchild(category); //method 2 xmlelement category2 = xmldoc.createelement("category"); string catdata = string.format("<categoryid>{0}</categoryid><categoryname>{1}</categoryname>", "7", "adding data innerxml"); category2.innerxml = catdata; root.appendchild(category2); xmldoc.save(inputfile); }
for further reading refer xmldocument , xmlnode
using system.linq.xml following shall help:
static void main(string[] args) { string inputfile = @"d:\temp\cat.xml"; xdocument xmldoc = xdocument.load(inputfile); xelement root = xmldoc.root; root.add(new xelement("category", new xelement("categoryid", "8"), new xelement("categoryname", "added linqxml"))); xmldoc.save(inputfile); }
also can refer this answer.
edit: how change value of element
static void main(string[] args) { string inputfile = @"d:\temp\cat.xml"; xdocument xmldoc = xdocument.load(inputfile); xelement root = xmldoc.root; string val = "5"; ienumerable<xelement> vls = e in root.elements("category") e.element("categoryid").value.equals(val) select e; if (vls.count() == 1) { vls.elementat(0).element("categoryname").value = "value has been changed"; } xmldoc.save(inputfile); }
to further learn refer this link.
Comments
Post a Comment