简体   繁体   中英

LINQ - Specified elements not being removed from XML file

I have an XML file:

<?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):

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. 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 .

@DavidTunnell what is your root xml element that contains everything you need? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM