尝试编写时出错,然后在Windows Phone 8应用程序中读取XML文件

时间:2014-04-07 18:23:38

标签: c# xml windows-phone-8

编辑:添加自我发布以来收集的所有信息。

你好堆垛机! 我第一次尝试使用Visual Studio 2013和WP8 SDK进行Metro风格的Windows Phone 8应用程序。

此应用应该能够存储app文件夹中存储的XML文件中的一些用户数据。

这是它应该做的:

用户以正常方式使用应用程序,然后保存数据。我想将它添加到一个dataFile.xml文件中,该文件只使用xml声明行和根元素创建。然后,如果用户想要查看他保存的内容,应用程序应该获取XML文件中的数据并显示它。

这是基本的XML文件:

<?xml version="1.0" encoding="utf-8" ?>
<itemList>

</itemList>

我编写数据的代码:(来自编辑的修改)

var isoFileStream = new IsolatedStorageFileStream("Saves\\itemList.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite, store); //Where store is my definition of IsolatedStorageFile
var xDoc = XDocument.Load(isoFileStream);
                    var newItem = new XElement("Item",
                            new XElement("Name", ItemName.Text),
                            //all other elements here
                            new XElement("Method", method));
        xDoc.Root.Add(newItem);
        xDoc.Root.Save(isoFileStream);
        isoFileStream.Close();

感谢IsolatedStorage和ISETool.exe,我可以使用上面的代码在其中写入之后检索xml文件。结果如下:

<?xml version="1.0" encoding="utf-8" ?> <itemList></itemList><?xml version="1.0" encoding="utf-8"?>
    <itemList>
        <Item>
            <Name>My Item</Name>
            <Method>Item method</Method>
        </Item>
    </itemList>

因此,为了恢复,代码加载了上面显示的xml文件,使用xDoc.Root检测到根元素,并在其中添加了项目。但是,在保存时,它会重新创建XML声明和根元素,从而使文件结构不正确,因此无法使用。为什么?好问题。怎么解决?这就是我想知道的。

有什么想法吗?

提前多多感谢:)

1 个答案:

答案 0 :(得分:0)

我终于找到了如何解决这个问题,所以我回答了我自己的问题,万一有人遇到同样的问题。

问题在于:

xDoc.Root.Save(isoFileStream);

这使用用于加载XML文件的先前内容的文件流来保存在代码中格式化的XDocument。但是,即使文件为空,XDocument.Save函数也可以格式化XML文件。因此,它将数据写入文件的末尾,通过添加两个声明使结构不正确。

解决方案是使用XDocument.load(fileStream)在var xDoc中收集XML内容,然后关闭流并打开一个新文件,将FileMode选项设置为Create,以覆盖现有文件:

var isoFileStream = new IsolatedStorageFileStream("Saves\\itemList.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite, store);
var xDoc = XDocument.Load(isoFileStream);
isoFileStream.Close();
isoFileStream = new IsolatedStorageFileStream("Saves\\itemList.xml", FileMode.Create, FileAccess.ReadWrite, store);
                    var newItem = new XElement("Item",
                            new XElement("Name", ItemName.Text),
                            //all other elements here
                            new XElement("Method", method));
        xDoc.Root.Add(newItem);
        xDoc.Save(isoFileStream);
        isoFileStream.Close();

使用此功能完美无缺。感谢那些回答他们帮助的人:)