0

I add .xml file to my roject. Now I need to open it. I try FileStream, StreamReader, IsolatedStorageFileStream. But there are get exception in each case. Somebody know how can i open local xml file and get data from it?

    public static AllFlags Load()
    {
        IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
        AllFlags allFlags;

        IsolatedStorageFileStream stream = storage.OpenFile(filename, FileMode.Open);
        //StreamReader stream = new StreamReader(filename);
        XmlSerializer xml = new XmlSerializer(typeof(AllFlags));
        allFlags = xml.Deserialize(stream) as AllFlags;
        stream.Close();
        stream.Dispose();

        return allFlags;
    }
4

2 回答 2

0

假设您已经在 WP8 项目中创建了文件夹 XmlFiles(在根级别)。您可以像这样加载xml:

var doc = XElement.Load("XmlFiles/NameOfXmlFile.xml");

请注意,没有前导../字符。另外,检查 xml 文件的属性。Build Action 必须设置为Content并且 Copy to Output Directory 应该是Copy if newerCopy always

于 2014-01-11T13:01:04.017 回答
0

如果您不需要 xml 特定信息,而只是读取文件的内容,这是最简单的方法:http: //msdn.microsoft.com/en-us/library/system.io.file.readalltext.aspx

System.IO.File.ReadAllText(@"drive:\path\to\your\file.xml");

否则,框架中有指定的 xml 对象来执行此操作。通常你会使用XmlDocument. 请参见下面的示例。

http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.loadxml.aspx获得

using System;
using System.Xml;

public class Sample {

  public static void Main() {

    // Create the XmlDocument.
    XmlDocument doc = new XmlDocument();
    doc.Load(@"drive:/path/to/you/file.xml");

    //Get data from the Xml File
    XmlNode Node = doc.SelectSingleNode("/apple/price");

   // Add a price element.
   XmlElement newElem = doc.CreateElement("price");
   newElem.InnerText = "10.95";
   doc.DocumentElement.AppendChild(newElem);

    // Save the document to a file and auto-indent the output.
    XmlTextWriter writer = new XmlTextWriter("data.xml",null);
    writer.Formatting = Formatting.Indented;
    doc.Save(writer);
  }
}

还可以将此链接视为一个很好的教程: http: //www.codeproject.com/Articles/169598/Parse-XML-Documents-by-XMLDocument-and-XDocument

于 2013-08-07T11:20:49.470 回答