删除XML元素节点

时间:2014-02-19 20:51:21

标签: c# xml windows-phone-8

我想使用C#删除本地xml文件中的Element Node及其所有Child Elements

这是我的xml文件:

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

我想删除一个鸡尾酒元素,其中id-attribute为4,存储在变量中。 如何告诉我的应用程序只需删除id为4的鸡尾酒元素? XmlNode.RemoveChild无效,因为Windows Phone 8不支持/不可用。 我编写了以下代码,但我仍然坚持在哪里写我要删除的元素的id。

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);
            }
        }
    }
}

3 个答案:

答案 0 :(得分:6)

  

我想删除一个鸡尾酒元素,其中id-attribute为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();

或使用XPATH

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

答案 1 :(得分:0)

我建议您使用XDocument代替XmlReader。在这种情况下,任务将更容易。

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

答案 2 :(得分:0)

我只将XmlReader用于大型xml文件。 使用XmlDocument或更好的XDocument可以更轻松地搜索和操作xml文件。