C# 如何删除windows phone中的xml元素

C# 如何删除windows phone中的xml元素,c#,xml,windows-phone-8,C#,Xml,Windows Phone 8,在创建xml并向其中添加数据和元素之后,我希望能够从中删除特定的元素。我试着从这里跟随它所说的,然后我就可以从中去除任何元素;然而,它并没有完全移除该元素;因此,它对我的xml文件产生了一个错误 我的示例xml如下(删除前) 以下是我执行此操作的代码: var storage = IsolatedStorageFile.GetUserStoreForApplication(); fileName = "Favorite\\Favorite.xml"; XDocument docx = null;

在创建xml并向其中添加数据和元素之后,我希望能够从中删除特定的元素。我试着从这里跟随它所说的,然后我就可以从中去除任何元素;然而,它并没有完全移除该元素;因此,它对我的xml文件产生了一个错误

我的示例xml如下(删除前)

以下是我执行此操作的代码:

var storage = IsolatedStorageFile.GetUserStoreForApplication();
fileName = "Favorite\\Favorite.xml";
XDocument docx = null;
using (IsolatedStorageFileStream isoStreamx = new IsolatedStorageFileStream(fileName, FileMode.Open, storage))
{
   // isoStreamx.Position = 0;
    docx = XDocument.Load(isoStreamx);

    isoStreamx.SetLength(docx.ToString().Length);

    docx.Root.Elements().Where(x => x.Attribute("pro_id").Value == NavigationContext.QueryString["id"] as string).Remove();

    isoStreamx.Position = 0;
    docx.Save(isoStreamx);
}

如何完全删除元素?请帮帮我,谢谢。

您当前正在重复使用同一个流来进行“顶部保存”。这只会覆盖数据,不会截断文档结尾处的文件。您真正想要做的是有效地创建一个新文件。比如:

var storage = IsolatedStorageFile.GetUserStoreForApplication();
fileName = "Favorite\\Favorite.xml";
XDocument docx = null;
using (var isoStreamx = new IsolatedStorageFileStream(fileName, FileMode.Open, storage))
{
    docx = XDocument.Load(isoStreamx);
}

var target = (string) NavigationContext.QueryString["id"];
docx.Root
    .Elements()
    .Where(x => x.Attribute("pro_id").Value == target)
    .Remove();

using (var isoStreamx = new IsolatedStorageFileStream(fileName, FileMode.Create, storage))
{
    docx.Save(isoStreamx);
}

您可以保留当前代码,只需在结束时调用
isoStreamx.SetLength(isoStreamx.Position)
(删除当前无意义且中断的
SetLength
call)-但我认为使用上述代码更干净。

谢谢您的帮助回答:)
var storage = IsolatedStorageFile.GetUserStoreForApplication();
fileName = "Favorite\\Favorite.xml";
XDocument docx = null;
using (IsolatedStorageFileStream isoStreamx = new IsolatedStorageFileStream(fileName, FileMode.Open, storage))
{
   // isoStreamx.Position = 0;
    docx = XDocument.Load(isoStreamx);

    isoStreamx.SetLength(docx.ToString().Length);

    docx.Root.Elements().Where(x => x.Attribute("pro_id").Value == NavigationContext.QueryString["id"] as string).Remove();

    isoStreamx.Position = 0;
    docx.Save(isoStreamx);
}
var storage = IsolatedStorageFile.GetUserStoreForApplication();
fileName = "Favorite\\Favorite.xml";
XDocument docx = null;
using (var isoStreamx = new IsolatedStorageFileStream(fileName, FileMode.Open, storage))
{
    docx = XDocument.Load(isoStreamx);
}

var target = (string) NavigationContext.QueryString["id"];
docx.Root
    .Elements()
    .Where(x => x.Attribute("pro_id").Value == target)
    .Remove();

using (var isoStreamx = new IsolatedStorageFileStream(fileName, FileMode.Create, storage))
{
    docx.Save(isoStreamx);
}