JelleKerkstra
JelleKerkstra

Reputation: 512

Deleting XML element nodes

I want to delete an Element Node and all its Child Elements in a local xml-file by using C#.

This is my xml-file:

<?xml version="1.0" encoding="UTF-8"?>
<data>
  <cocktail name="43 Hedonism" id="14">
    <name>43 Hedonism</name>
    <id>14</id>
  </cocktail>
  <cocktail name="B-52" id="4">
    <name>B-52</name>
    <id>4</id>
  </cocktail>
</data>

I want to remove a cocktail Element where the id-attribute is 4, which is stored in a variable. How can I tell my app that it only has to delete the cocktail Element where the id is 4? XmlNode.RemoveChild will not work since it isn't supported/available in Windows Phone 8. I wrote the following code but I'm stuck on where to write the id of the element I want to remove.

using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Resources;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using XmlLocalDelete1.Resources;
using System.Xml;
using System.Xml.Linq;
using System.Text;

namespace XmlLocalDelete1
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
        }

        private string id = "4";

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                tb1.Text = "";
                // copy the xml file to isolated storage
                using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!file.FileExists("bar.xml"))
                    {
                        StreamResourceInfo sr_en = Application.GetResourceStream(new Uri("Resources\\bar.xml", UriKind.Relative));
                        using (BinaryReader br_en = new BinaryReader(sr_en.Stream))
                        {
                            byte[] data = br_en.ReadBytes((int)sr_en.Stream.Length);
                            //Write the file.
                            using (BinaryWriter bw = new BinaryWriter(file.CreateFile("bar.xml")))
                            {
                                bw.Write(data);
                                bw.Close();
                            }
                        }
                    }

                    // work with file at isolatedstorage
                    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("bar.xml", FileMode.Open, file))
                    {
                        XDocument doc = XDocument.Load(stream, LoadOptions.None);

                        // delete node
                        XElement deleteThis = doc.Element("cocktail");
                        deleteThis.Remove();
                    }

                    //  Write remaining Xml to textblock

                    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("bar.xml", FileMode.Open, file))
                    {
                        //  Load the XML file
                        XmlReader reader = XmlReader.Create(stream);

                        while (reader.Read())
                        {
                            switch (reader.NodeType)
                            {
                                case XmlNodeType.Element: // Het knooppunt is een element.
                                    //tb1.Text = tb1.Text + "<" + reader.Name;
                                    while (reader.MoveToNextAttribute()) // Attributen lezen.
                                        tb1.Text = tb1.Text + " " + reader.Name + "='" + reader.Value + "'";
                                    //tb1.Text = tb1.Text + ">";
                                    break;
                                case XmlNodeType.Text: //De tekst in elk element weergeven.
                                    //tb1.Text = tb1.Text + reader.Value + "\r\n";
                                    Console.WriteLine(reader.Value);
                                    break;
                                case XmlNodeType.EndElement: //Het einde van het element weergeven.
                                    Console.Write("</" + reader.Name);
                                    Console.WriteLine(">");
                                    break;
                            }
                        }

                        reader.Close();
                    }
                }
            }
            catch (Exception myExc)
            {
                Console.WriteLine(myExc.Message);
            }
        }
    }
}

Upvotes: 2

Views: 1662

Answers (3)

Axel
Axel

Reputation: 1

I would use the XmlReader only for large xml files. Searching and manipulation xml files is much easier with XmlDocument or better XDocument.

Upvotes: 0

Vasily Semenov
Vasily Semenov

Reputation: 402

I would recommend you use XDocument instead XmlReader. In that case the task will be much easier.

XDocument xdoc = XDocument.Load(filename);
xdoc.Root.Elements().Where(x => x.Attribute("id").Value == "4").Remove();
xdoc.Save(filename);

Upvotes: 0

L.B
L.B

Reputation: 116138

I want to remove a cocktail Element where the id-attribute is 4,

var xDoc = XDocument.Load(filename); //or XDocument.Load(stream);
xDoc.Descendants("cocktail").First(c => c.Attribute("id").Value == "4").Remove();
string newXml = xDoc.ToString();

OR using XPATH

xDoc.XPathSelectElement("//cocktail[@id='4']").Remove();

Upvotes: 6

Related Questions