I am developing an app to manipulate XML in Windows Phone 8.1 RT. the code is below
private void btnXcute_tapped(object sender, TappedRoutedEventArgs e)
{
xmlmanipulation();
}
private async void xmlmanipulation()
{
Random rand = new Random();
try
{
var filex = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(@"xmlfile.xml");
XDocument xdoc = XDocument.Load(filex);
var word = xdoc.Descendants("word");
int max = word.Count();
txt1.Text = word.FirstOrDefault().Value.ToString();
txt1_Copy.Text = xdoc.Descendants("meaning").FirstOrDefault().Value.ToString();
//node removal part
xdoc.Root.Elements("wordset").Where(dim_word => dim_word.Element("word").Value == word.FirstOrDefault().Value.ToString() && dim_word.Element("meaning").Value == xdoc.Descendants("meaning").FirstOrDefault().Value.ToString())
.FirstOrDefault().Remove();
//file overwriting part
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("xmlfile.xml", CreationCollisionOption.ReplaceExisting);
using (var stream = await file.OpenStreamForWriteAsync())
{
xdoc.Save(stream); // Save XDocument into the stream
stream.Position = 0;
}
}
catch (Exception s)
{
txt1.Text = s.Message;
txt1_Copy.Text = s.Source;
}
}
I have placed the XML file(xmlfile.xml) in the project main folder as below
But I get The system cannot find the file specified. (Exception from HRESULT:0x80070002)
and the Exception source is mscorlib
.
I am very new to XML manipulation. Please help me. All I need to read an XML file, remode a the very first <wordset>
element on it, save the file (overwrite) on a button click. I have total 4 <wordset>
elements and if I press the button 4 times, all the elements will be removed in the file.
My XML file is
<?xml version="1.0" encoding="utf-8" ?>
<xmlfile>
<wordset>
<word>word1</word>
<meaning>meaning1</meaning>
</wordset>
<wordset>
<word>word2</word>
<meaning>meaning2</meaning>
</wordset>
<wordset>
<word>word3</word>
<meaning>meaning3</meaning>
</wordset>
<wordset>
<word>word4</word>
<meaning>meaning4</meaning>
</wordset>
</xmlfile>
You are trying to access file from Installed location not LocalFolder (depending on file's build action). Therefore you should use:
You can also take a look at this answer.