简体   繁体   中英

Delete a specific XML element and its child elements in C#

Say I have this XML File:

<Stops>
    <Stop>
        <ID>1022</ID>
        <UserDescription>Test</UserDescription>
    </Stop>
    <Stop>
        <ID>1053</ID>
        <UserDescription>Test1045</UserDescription>
    </Stop>
</Stops>

I want to delete the entire node where the ID is equal to a value.

So eg deleting the node with 1022 should give:

<Stops>
    <Stop>
        <ID>1053</ID>
        <UserDescription>Test1045</UserDescription>
    </Stop>
</Stops>

The code I've been trying so far (C# in Windows Phone). It seems to malform and make the XML unreadable. I don't know where I'm going wrong...

        using (isoStore)
        {
            XDocument doc;
            using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(StopFileName, FileMode.Open, isoStore))
            {
                doc = XDocument.Load(isoStream, LoadOptions.None);
                doc.Descendants("Stop")
                      .Where(x => (string)x.Element("ID") == "1022").Remove();

                doc.Save(isoStream);
            }
        }

I think your error is reading and saving using the same stream.

If you look at your own code you load the xml from your file:

doc = XDocument.Load(isoStream, LoadOptions.None);

And then save to the same stream:

doc.Save(isoStream);

So you end up with an XML File looking like this

<Stops>
    <Stop>
        <ID>1022</ID>
        <UserDescription>Test</UserDescription>
    </Stop>
    <Stop>
        <ID>1053</ID>
        <UserDescription>Test1045</UserDescription>
    </Stop>
</Stops>
<Stops>
    <Stop>
        <ID>1053</ID>
        <UserDescription>Test1045</UserDescription>
    </Stop>
</Stops>

And having 2 root elements would indeed cause a "Unexpected XML declaration"

I would change your code so first you read the file, and then creates a new file / overwrites an existing file.

        using (isoStore)
        {
            XDocument doc;
            using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(StopFileName, FileMode.Open, isoStore))
            {
                doc = XDocument.Load(isoStream, LoadOptions.None);
            }

            doc.Descendants("Stop")
                      .Where(x => (string)x.Element("ID") == "1022").Remove();

            using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(StopFileName, FileMode.Create, isoStore))
            {
                doc.Save(isoStream);
            }
        }

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