简体   繁体   English

Windows Phone 8.1 XDocument xml序列化C#

[英]Windows phone 8.1 XDocument xml serialization C#

I'm creating a Windows Phone 8.1 app, and I need to serialize my data to XML. 我正在创建Windows Phone 8.1应用程序,并且需要将数据序列化为XML。

I have two functions; 我有两个职能; the first one is creating a document where I can later put my retrieved data. 第一个是创建一个文档,以后可以在其中放置检索到的数据。

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

The second one is making serialization to my xml file: 第二个是对我的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);


            }
    }

The first xml function is making this code: 第一个xml函数正在编写以下代码:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root />

When I'm running the second function I've got this error: root element is missing . 当我运行第二个函数时,出现以下错误: root element is missing Can anyone tell me how I can get this serialization to work? 谁能告诉我如何使此序列化工作?

Try this, you might need to doctor it a bit: 尝试此操作,您可能需要稍微尝试一下:

1) create the document 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) write the new data to the document 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM