【问题标题】:Editing Xml file in C# (WP8)在 C# (WP8) 中编辑 Xml 文件
【发布时间】:2014-02-19 11:43:21
【问题描述】:

我正在尝试在 C# 中为我的 Windows Phone 8 应用程序编辑本地 xml 文件。 在网上,我找到了无数使用XmlDocument 的例子,使用了AppendChild 之类的方法。 在 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>

【问题讨论】:

  • I tried the code below but get some error on protected override void - 什么是some error
  • 您的 xml 文件在哪里?看起来,就像它在资源中一样,我不确定,你可以在 windows-phone 中编辑一个文件。如果要编辑此文件,应将其复制到独立存储,然后使用该副本。
  • 也许在那个断点处,您将鼠标移到 myExc 上并向我们提供 MessageStackTrace 的值?
  • This operation would create an incorrectly structured document。抱歉,我之前没有发布过这个,但我是 C# 新手。

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


【解决方案1】:

好的,这里给你一个样本。

我强烈建议您使用 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 声明。XML 声明必须是文档中的第一个节点,并且在它之前不允许出现空白字符。第 11 行,位置 10。"将xml文件写入IsolatedStorage时是否可能添加了字节顺序标记?如果是这样,我怎样才能在这段代码中轻松删除它?
  • @JelleKerkstra,要查看更改的文件,您应该使用 Visual Studio 的独立存储资源管理器扩展(其中有几个,都是免费的)。但是,IS 资源管理器是为使用真实手机设备而创建的(给定的屏幕截图显示,您正在使用模拟器),因此您可能会遇到一些问题。您收到的错误很可能是“
【解决方案2】:

您当前的代码将在 xml 文件中添加另一个 &lt;data&gt; 元素,从而导致 xml 具有多个根元素,这不是有效的 xml 格式。我猜您想将另一个 &lt;cocktail&gt; 元素添加到现有的 &lt;data&gt; 元素中。如果是这种情况,您可以尝试这种方式:

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

【讨论】:

    猜你喜欢
    • 2011-05-14
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    相关资源
    最近更新 更多