如何让我的Silverlight项目读取我的xml文件?

时间:2014-03-17 07:59:28

标签: c# xml silverlight

我有一个大问题。我必须在Silverlight中进行一个具有不同难度的测验。我从不使用这个框架,现在我尝试学习。首先,我尝试用这个框架读取我的xml文件,并使用c#作为编程语言。 我写了这段代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
using System.Data;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace quiz4
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            var quizzes = new List<Quiz>();
            var objSettings = new XmlReaderSettings();
            objSettings.IgnoreWhitespace = true;
            objSettings.IgnoreComments = true;
            const string booksFile = @"D:\quiz.xml";
            string element = "";

            using (XmlReader objReader = XmlReader.Create(booksFile, objSettings))
            {
                bool isLastElement = false;
                var quiz = new Quiz();
                var dx = new List<Answers>();

                while (objReader.Read())
                {

                    if (objReader.NodeType == XmlNodeType.Element)
                    {
                        element = objReader.Name;
                        if (element == "question")
                        {
                            quiz = new Quiz();
                            dx = new List<Answers>();
                            isLastElement = true;
                        }
                    }
                    else if (objReader.NodeType == XmlNodeType.Text)
                    {
                        switch (element)
                        {
                            case "questionText":
                                quiz.QuestionText = objReader.Value;
                                //Console.WriteLine("questionText: " + objReader.Value);
                                break;
                            case "LEVEL":
                                quiz.Level = objReader.Value;
                                //Console.WriteLine("LEVEL  " + objReader.Value);
                                break;
                            case "correct":
                                dx.Add(new Answers() { IsCorrect = true, AnswerName = objReader.Value });
                                //Console.WriteLine("correct: " + objReader.Value);
                                break;
                            case "incorrect":
                                dx.Add(new Answers() { IsCorrect = false, AnswerName = objReader.Value });
                                //Console.WriteLine("incorrect: " + objReader.Value);
                                break;
                        }
                    }

                    if (isLastElement)
                    {
                        quiz.AnswerList = dx;
                        quizzes.Add(quiz);
                        isLastElement = false;
                    }

                }
            }

        }

        class Quiz
        {
            public string QuestionText;
            public string Level;
            public List<Answers> AnswerList;//lista de raspunsuri
        }

        public class Answers
        {
            public bool IsCorrect;//raspuncul poate fi adevarat(true) sau false.
            public string AnswerName;//raspunsul
        }

XML文件:

<?xml version="1.0" encoding="utf-8" ?>
<quiz>
<question>
<questionText>In Oracle SQL * PLUS, functia LOWER (col/value) permite:</questionText>
<LEVEL>2</LEVEL> 
<correct>fortarea caracterelor scrise cu litere mari sau mixte, in caractere scrise cu litere mici</correct>
<incorrect>fortarea caracterelor scrise cu litere mici in caractere scrise cu litere maric)</incorrect>
<incorrect>returnarea numarului de caractere din coloana sau valoarea literalad)</incorrect>
<incorrect>translatarea lungimii caracterelor dintr-o coloana/valoare la o lungime specificata</incorrect>
</question>

<question>
<questionText>In Oracle SQL * PLUS, functia INITCAP permite:</questionText>
<LEVEL>1</LEVEL> 
<incorrect>transformarea oricarei litere a unui cuvant, in litera mare</incorrect>
<correct>transformarea primei litere a fiecarui cuvant/coloana in litera mare</correct>
<incorrect>transformarea unei litere specificate a unui cuvant , intr-o litera mare </incorrect>
<incorrect>este o similitudine cu alte SGBD si nu exista specificata in SQL*PLYS</incorrect>
</question>
</quiz>

当我按F5时没有任何事情发生。为什么?有人能帮我吗?谢谢!

2 个答案:

答案 0 :(得分:0)

Silverlight正在浏览器的沙箱中运行,您的应用程序无法访问本地文件系统(例如D:\quiz.xml)。您必须将Silverlight应用程序安装为trusted application才能获得对本地文件系统的完全访问权限。

如果您设法在Silverlight中绕过此限制,则应对您的应用程序进行另一项更改。现在,您正在MainPage类的构造函数中读取XML(并且由于我已经描述了限制,因此抛出异常)。您应该将此代码移动到事件处理程序(例如,Loaded事件),但您还应确保使用异步方法完成任何文件系统或网络访问。例如,UI在异步回调中更新。

如果您正在学习C#,您会发现编写Silverlight应用程序会使焦点远离简单地学习该语言,因为Silverlight会施加额外的限制。

答案 1 :(得分:0)

如前面的回答所述,您无法直接从Silverlight中的本地文件结构访问文件。您通常这样做的方法是在Web服务器上托管文件(在您的情况下是quiz.xml),然后让Silverlight调用Web服务器来获取文件。您可以在托管Silverlight应用程序的同一Web服务器上托管该文件。这是异步完成的,您可以在构造函数中启动此调用。另一件事是你读取xml文件的方式,它看起来有点奇怪,我更喜欢使用Linq来XML。所以这就是我要做的事情:

public partial class MainPage : UserControl
{
        private List<Quiz> quizzes;

        public MainPage()
        {
            InitializeComponent();

            var xmlUri = new Uri("http://yoursite.com/quiz.xml");
            var downloader = new WebClient();

            downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(downloader_OpenReadCompleted);
            downloader.OpenReadAsync(xmlUri);
        }


        void downloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
           if (e.Error == null)
           {
              Stream responseStream = e.Result;

               using (var reader = XmlReader.Create(responseStream))
               {
                  var doc = XDocument.Read(reader);

                  quizzes = doc.Descendants("question")
                            .Select(q => new Quiz 
                            {
                               QuestionText = q.Element("questionText").Value, 
                               Level = q.Element("LEVEL").Value,
                               AnswerList = q.Descendants("incorrect")
                                             .Select(i => new Answers 
                                             { 
                                                IsCorrect = false, 
                                                AnswerName = i.Value 
                                             })
                                             .Union(
                                                q.Descendants("correct")
                                                 .Select(i => new Answers 
                                                 { 
                                                    IsCorrect = true, 
                                                    AnswerName = i.Value 
                                             })).ToList()

                            }).ToList();      
               }
           }
        }         
    }