[英]Windows phone 8.1 XDocument xml serialization C#
我正在创建Windows Phone 8.1应用程序,并且需要将数据序列化为XML。
我有两个职能; 第一个是创建一个文档,以后可以在其中放置检索到的数据。
public async Task make()
{
using (var questions = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(
"data.xml",
CreationCollisionOption.OpenIfExists))
{
XDocument xml = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Root")
);
xml.Save(questions);
}
}
第二个是对我的xml文件进行序列化:
public async Task serial(Tsk tak)
{
using (var questions = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(
"data.xml",
CreationCollisionOption.OpenIfExists))
{
XDocument xml = XDocument.Load(questions);
xml.Root.Add(new XAttribute("Date", tak.Date),
new XElement("time", tak.Time),
new XElement("text", tak.Text)
);
xml.Save(questions);
}
}
第一个xml函数正在编写以下代码:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root />
当我运行第二个函数时,出现以下错误: root element is missing
。 谁能告诉我如何使此序列化工作?
尝试此操作,您可能需要稍微尝试一下:
1)创建文件
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("root");
doc.AppendChild(root);
file = await ApplicationData.Current.LocalFolder.CreateFileAsync("data.xml");
await FileIO.WriteTextAsync(file, doc.GetXml());
Debug.WriteLine("Done creating file.");
2)将新数据写入文档
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("data.xml");
XDocument doc = XDocument.Load(file.Path);
XElement newQuestion = new XElement("Question",
new XElement("time", tak.Time),
new XElement("text", tak.Text)
).SetAttributeValue("Date", tak.Date);
doc.Root.Add(newQuestion);
await FileIO.WriteTextAsync(file, doc.Root.ToString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.