C# Windows phone 8.1 XDocument xml序列化C
我正在创建一个Windows Phone 8.1应用程序,需要将数据序列化为XML 我有两个功能;第一个是创建一个文档,我可以在其中放置检索到的数据C# Windows phone 8.1 XDocument xml序列化C,c#,xml,serialization,windows-phone-8.1,windows-phone,C#,Xml,Serialization,Windows Phone 8.1,Windows Phone,我正在创建一个Windows Phone 8.1应用程序,需要将数据序列化为XML 我有两个功能;第一个是创建一个文档,我可以在其中放置检索到的数据 public async Task make() { using (var questions = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync( "data.xml", Cr
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 />
当我运行第二个函数时,我遇到了这样一个错误:根元素丢失。有人能告诉我怎样才能让这个序列化工作吗 试试这个,你可能需要稍微调整一下: 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.");
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());
2将新数据写入文档
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.");
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());
是一个空元素。我猜您需要向元素添加值或子元素。打开文件并读取到结尾后,您将追加到该文件。您需要倒带,然后截断您的流。可能重复:现在我得到另一个错误uri参数必须是文件系统相对路径在哪一行?GetFileAsync或CreateFileAsync的路径可能格式不正确。如果将路径更改为包含未正确转义的子目录,或将其更改为远程位置。你现在的路径是什么样子的?路径错了。非常感谢你的帮助