繁体   English   中英

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

[英]Editing Xml file in C# (WP8)

我正在尝试为Windows Phone 8应用程序在C#中编辑本地xml文件。 在网上,我发现了使用诸如AppendChild方法使用XmlDocument无数示例。 在Windows Phone 8中, XmlDocument已被XDocument取代, AppendChild消失了。 我尝试了以下代码,但在protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)上遇到一些错误:可以在此处看到错误: http : protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) 。 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>

好的,这里有您的样品。

我强烈建议您使用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);
                }
            }

您当前的代码将向XML文件中添加另一个<data>元素,从而导致具有多个根元素的xml是无效的xml格式。 我想您想向现有的<data>元素添加另一个<cocktail>元素。 如果是这样,您可以尝试以下方式:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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