在C#中编辑Xml文件(WP8)

时间:2014-02-19 11:43:22

标签: c# .net xml linq windows-phone-8

我正在尝试在C#中为我的Windows Phone 8应用编辑本地xml文件。 在网络上,我找到了无数使用XmlDocumentAppendChild等方法的示例。 在Windows Phone 8中,XmlDocument已被XDocument取代,AppendChild消失了。 我尝试了下面的代码,但在protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)上收到了一些错误: 错误可以在这里看到:http://i811.photobucket.com/albums/zz38/JelleK1996/cerror1_zpsb6aa5398.png

任何人都可以帮助我吗?

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

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

            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                XmlWriterSettings xws = new XmlWriterSettings();
                xws.OmitXmlDeclaration = true;
                xws.Indent = true;

                using (XmlWriter xw = XmlWriter.Create(sb, xws))
                {
                    XDocument xdoc = XDocument.Load("Resources/bar.xml");
                    XElement xmlTree = new XElement("data",
                        new XElement("cocktail",
                            new XElement("name", "Dreamsicle"),
                            new XElement("id", 1)
                        )
                    );
                    xdoc.Add(xmlTree);
                    xdoc.Save(xw);
                }

                //xdoc.Add(xmlTree);
                //xdoc.Save("Resources/bar.xml", SaveOptions.None);

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

        /*private static XElement CreateCocktail(XDocument xmlDoc,
                                                string name,
                                                int id)
        {
            var xmlCocktail = xmlDoc
        }*/
    }
}

Xml文件:

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

2 个答案:

答案 0 :(得分:4)

好的,这里有一个样品给你。

我强烈建议您使用IsolatedStorage而不是在资源中编辑文件。

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

                    // add new node to data section
                    doc.Descendants("data").FirstOrDefault().Add(
                        new XElement("cocktail",
                            new XElement("name", "Dreamsicle"),
                            new XElement("id", 1)
                        )
                    );
                    // prevent xml file from doubling nodes
                    if (stream.CanSeek)
                        stream.Seek(0, SeekOrigin.Begin);
                    doc.Save(stream);
                }
            }

答案 1 :(得分:0)

您当前的代码会将另一个<data>元素添加到xml文件中,从而生成一个具有多个根元素的xml,这些元素不是有效的xml格式。我想您想要将另一个<cocktail>元素添加到现有的<data>元素中。如果是这种情况,您可以尝试这种方式:

.......
XDocument xdoc = XDocument.Load("Resources/bar.xml");
XElement xmlTree = new XElement("cocktail",
        new XElement("name", "Dreamsicle"),
        new XElement("id", 1)
    );
//add new <cocktail> to existing root, which is <data> element
xdoc.Root.Add(xmlTree);
xdoc.Save(xw);
.......