我是WP7的新手。我按照本教程阅读和编写了一个xml文件,但当我阅读xml文件时,它只显示了xml文件的最上面一行。我不知道如何检查程序是否正确编写了xml文件。所以。
1.在哪里检查保存在隔离存储中的xml文件。
2.如何摆脱这个问题。
我在独立存储中编写Xml文件的代码:
using (IsolatedStorageFile myIsolatedStorage =
IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("mz1.xml", FileMode.Create, myIsolatedStorage))
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(isoStream, settings))
{
writer.WriteStartDocument();
writer.WriteStartElement("person");
writer.WriteElementString("node1", "value1");
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
}
}
}
从独立存储读取Xml文件的代码:
using (IsolatedStorageFile myIsolatedStorage =
IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream isoFileStream =
myIsolatedStorage.OpenFile("mz1.xml", FileMode.Open);
using (StreamReader reader = new StreamReader(isoFileStream))
{
textBlock1.Text= reader.ReadToEnd();
}
}
输出:
<?xml version="1.0" encoding="utf-8"?>
为了回答您的第一个问题,您可以从codeplex下载并安装WP7独立存储资源管理器:http://wp7explorer.codeplex.com/
它真的很容易使用。只需在app.xaml.cs中添加几行代码,就可以完成所有操作。
关于你的第二个问题,你那里的代码看起来还可以。我最近写了一个WP7应用程序,也做了这种事情。以下是一些代码:
public List<Task> GetTasks()
{
var tasks = new List<Task>();
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.FileExists(XmlFile))
{
//store.DeleteFile(XmlFile);
//XDocument doc = XDocument.Load(store.OpenFile(XmlFile, FileMode.Open));
using (var sr = new StreamReader(new IsolatedStorageFileStream(XmlFile, FileMode.Open, store)))
{
XDocument doc = XDocument.Load(sr);
tasks = (from d in doc.Descendants("task")
select new Task
{
Category = (string) d.Attribute("category"),
Id = (string) d.Attribute("id"),
Name = (string) d.Element("name"),
CreateDate = (DateTime) d.Element("createdate"),
DueDate = (DateTime) d.Element("duedate"),
IsComplete = (bool) d.Element("isComplete")
}).ToList<Task>();
}
}
}
return tasks;
}
这取决于您,但您可能需要考虑使用LinqToXml。这让事情变得更干净了。
事实上,我有一篇博客文章,在这里发布了所有这些:
http://www.ritzcovan.com/2012/02/building-a-simple-windows-phone-apppart-2/
你也可以下载所有的代码。我希望你觉得它有帮助。
您的代码执行良好。我已经将结果更改为不在TextBlock中设置,而是设置为字符串变量,它输出以下内容:
<?xml version="1.0" encoding="utf-8"?>
<person>
<node1>value1</node1>
</person>
我想TextBlock只是显示了结果的第一行。
你在找这样的东西吗?