0

我正在尝试开发 Windows 7 Phone,并且正在使用需要解析然后执行 Linq 查询的 XML 文件。

问题是这样的:

每当我尝试访问该文件(它存储在本地)时,它都会返回一个错误,指出无法找到该文件,因为它不是 XAP 包的一部分。

我尝试了另一种我使用的解决方案,StreamReader但我仍然收到一个类似的错误:

尝试访问方法失败 System.IO.File.OpenText(System.String)

这是我正在使用的代码:

using (StreamReader reader = File.OpenText("C:/Users/Desktop/Assign/obj/Debug/buildings.kml"))
        {
            var xdoc = XDocument.Load ("buildings.kml");
            XNamespace kml = "http://www.opengis.net/kml/2.2";

            var dict = xdoc.Descendants(kml + "Placemark")
                          .ToDictionary(d => d.Element(kml + "name").Value,
                          d => d.Element(kml + "id").Value);

            foreach (var b in dict) {
                Console.WriteLine ("Building Name -> " + b.Key + " Building ID -> " + b.Value);
            }
        }

该文件位于:> C:/Users/Desktop/Assign/obj/Debug/buildings.kml 所以我看不到问题所在。在 Visual Studio 之外,我可以很好地读取 .xml 文件。

希望有人可以帮助

编辑:

新代码 -

Dictionary<string, string> getBuildingNames()
    {
        Uri uri = new Uri(@"Data\mydata.kml", UriKind.Relative);

        StreamResourceInfo sri = Application.GetResourceStream(uri);

        StreamReader sr = new StreamReader(sri.Stream);

        var xdoc = XDocument.Load(sr);
        XNamespace kml = "http://www.opengis.net/kml/2.2";

        var dict = xdoc.Descendants(kml + "Placemark")
                      .ToDictionary(d => d.Element(kml + "name").Value,
                      d => d.Element(kml + "id").Value);


        return dict;


    }

错误:-'NullReferenceException 未处理'

4

2 回答 2

4

Assuming you really are trying to do this as part of a WP7 project (rather than some non-mobile project related to it, e.g. preprocessing) you shouldn't be using File.OpenText.

Options:

于 2013-01-25T15:29:48.317 回答
1

Just a couple of some more tips to help you along:

1) Change the Build action property of the xml file to "Content". (Select the file and go to the properties window in Visual Studio)

2) If you only want to read from the file, then there is no need to have the file in IsolatedStorage. You can simply read it if you correctly set the Build Action property.

You can use XDocument to read the file.

XDocument xdoc = XDocument.Load(filepath);

where filepath is simply the relative path to the XML file, i.e. if you did not place it inside any folder in your project then it will be just the file name (assume it like being the root directory)

于 2013-01-25T18:49:16.930 回答