[英]LINQ - Specified elements not being removed from XML file
I have an XML file: 我有一个XML文件:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--QTabs Data Storage-->
<SyncTimes>
<LastSyncTime>
<id>1</id>
<SyncTime>3/31/2015 2:03:28 PM</SyncTime>
</LastSyncTime>
<LastSyncTime>
<id>2</id>
<SyncTime>3/31/2015 2:14:24 PM</SyncTime>
</LastSyncTime>
<LastSyncTime>
<id>3</id>
<SyncTime>3/31/2015 2:14:25 PM</SyncTime>
</LastSyncTime>
<LastSyncTime>
<id>4</id>
<SyncTime>3/31/2015 2:14:26 PM</SyncTime>
</LastSyncTime>
</SyncTimes>
All of the above times are earlier today I want to delete all LastSyncTime records before the current time (DateTime.Now): 以上所有时间都是今天早些时候,我想删除当前时间(DateTime.Now)之前的所有LastSyncTime记录:
public async void deleteArchivedSyncs()
{
var xElement = (from element in XMLDocObject.Elements("LastSyncTime")
where Convert.ToDateTime(element.Element("SyncTime").Value) < DateTime.Now
select element);
xElement.Remove();
storageFile = await storageFolder.GetFileAsync(Settings.xmlFile);
using (Stream fileStream = await storageFile.OpenStreamForWriteAsync())
{
XMLDocObject.Save(fileStream);
}
}
This being run does not effect the XML page. 运行该命令不会影响XML页面。 The desired elements are not being removed.
所需的元素不会被删除。 What am I doing wrong?
我究竟做错了什么?
This issue here appears to be that the only way to delete a child, is to have the parent do the deletion, as in: 这里的问题似乎是删除子项的唯一方法是让父项进行删除,如下所示:
class Program
{
public static void Main(params string[] args)
{
// test.xml contains OPs example content.
var xdoc = XDocument.Load(@"c:\temp\test.xml");
xdoc.Descendants("LastSyncTime")
.Where(e => Convert.ToDateTime(e.Element("SyncTime").Value) < DateTime.Now)
.Remove();
Console.WriteLine(xdoc);
xdoc.Save(@"c:\temp\test_filtered.xml");
}
}
This generates the following output: 这将产生以下输出:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--QTabs Data Storage-->
<SyncTimes />
Ie an empty root, which is to be expected, given that all dates are smaller than DateTime.Now
. 也就是说,鉴于所有日期都小于
DateTime.Now
,因此是空根。
@DavidTunnell what is your root xml element that contains everything you need? @DavidTunnell您包含所有所需内容的根xml元素是什么? in example:
例如:
//let's call the variable you use as Xdocument doc.
XmlNodeList nodes = doc.SelectNodes("LastSyncTime");
for (int i = nodes.Count - 1; i >= 0; i--)
{
nodes[i].ParentNode.RemoveChild(nodes[i]);
}
doc.Save(path);
This is how i had used hope it helps. 这就是我曾经希望对您有所帮助的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.