Tuesday, 1 October 2013

XML not well formed after deleting node using LINQ

XML not well formed after deleting node using LINQ

Original XML:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Links>
<Category name="a" />
<Category name="b" />
</Links>
I want to delete the category node whose attribute = "b" and I doing it
with the following code
using (IsolatedStorageFile myStore =
IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream myStream = new
IsolatedStorageFileStream(App.FileName, FileMode.Open,
FileAccess.ReadWrite, myStore))
{
XElement mainTree = XElement.Load(myStream);
mainTree.Elements("Category").Where(s =>
s.Attribute("name").Value == "b").DescendantsAndSelf().Remove();
myStream.Position = 0;
mainTree.Save(myStream);
}
}
After the code runs, the resulting XML looks like this...
<?xml version="1.0" encoding="utf-8"?>
<Links>
<Category name="a" />
</Links>="a" />
<Category name="b" />
</Links>
As you can see the XML is toast and cannot be read by the
IsolatedStorageFileStream reader and errors out.
Can you please tell me what I am doing wrong when deleting the node and
also when writing it back to the isolatedfilestorage?
Thanks in advance.

No comments:

Post a Comment