c# - Error when trying to write then read a XML file in Windows Phone 8 app -
edited : adding informations gathered since posted this.
hi stackers ! i'm trying first time metro style windows phone 8 app using visual studio 2013 , wp8 sdk.
this app should able store few data users in xml files stored in app folder.
here should :
the user use app normal way, , saves data. want add in datafile.xml file created xml declaration line , root element. then, if user want see saved, app should data in xml file , display it.
here basic xml file:
<?xml version="1.0" encoding="utf-8" ?> <itemlist> </itemlist>
and code write data : (modifications edit here)
var isofilestream = new isolatedstoragefilestream("saves\\itemlist.xml", filemode.openorcreate, fileaccess.readwrite, store); //where store definition of isolatedstoragefile var xdoc = xdocument.load(isofilestream); var newitem = new xelement("item", new xelement("name", itemname.text), //all other elements here new xelement("method", method)); xdoc.root.add(newitem); xdoc.root.save(isofilestream); isofilestream.close();
thanks isolatedstorage , isetool.exe, able retrieve xml file after writing inside using code above. here result :
<?xml version="1.0" encoding="utf-8" ?> <itemlist></itemlist><?xml version="1.0" encoding="utf-8"?> <itemlist> <item> <name>my item</name> <method>item method</method> </item> </itemlist>
so, resume, code loaded xml file shown above, detected root element using xdoc.root, , added item inside it. but, when saving, recreates xml declaration , root element, making file structure incorrect, unusable. why ? question. how fix ? that's love know.
any idea ?
thanks lot in advance :)
i found how deal this, i'm answering own question, in case have same problem.
the problem here :
xdoc.root.save(isofilestream);
this saves xdocument formatted in code using file stream used load previous content of xml file. xdocument.save function made format xml file usable if file empty. so, writes data @ end of file, making structure incorrect adding 2 declarations.
the solution gather xml content in var xdoc using xdocument.load(filestream), close stream , open new 1 filemode option set create, overwrite existing file :
var isofilestream = new isolatedstoragefilestream("saves\\itemlist.xml", filemode.openorcreate, fileaccess.readwrite, store); var xdoc = xdocument.load(isofilestream); isofilestream.close(); isofilestream = new isolatedstoragefilestream("saves\\itemlist.xml", filemode.create, fileaccess.readwrite, store); var newitem = new xelement("item", new xelement("name", itemname.text), //all other elements here new xelement("method", method)); xdoc.root.add(newitem); xdoc.save(isofilestream); isofilestream.close();
this working using this. ones answered :)
Comments
Post a Comment