【发布时间】: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 上并向我们提供
Message和StackTrace的值? -
This operation would create an incorrectly structured document。抱歉,我之前没有发布过这个,但我是 C# 新手。
标签: c# .net xml linq windows-phone-8