C# 如何让Silverlight项目读取xml文件?

C# 如何让Silverlight项目读取xml文件?,c#,xml,silverlight,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

我有个大问题。我必须在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
        }
使用系统;
使用System.Collections.Generic;
使用System.Linq;
Net系统;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Documents;
使用System.Windows.Input;
使用System.Windows.Media;
使用System.Windows.Media.Animation;
使用System.Windows.Shapes;
使用System.Windows.Browser;
使用系统数据;
使用System.Xml;
使用System.Xml.Linq;
使用System.IO;
命名空间quiz4
{
公共部分类主页面:UserControl
{
公共主页()
{
初始化组件();
var quizzes=新列表();
var objSettings=新的XmlReaderSettings();
objSettings.IgnoreWhitespace=true;
objSettings.IgnoreComments=true;
常量字符串booksFile=@“D:\quick.xml”;
字符串元素=”;
使用(XmlReader objReader=XmlReader.Create(booksFile,objSettings))
{
bool islasteElement=false;
var-quick=新测验();
var dx=新列表();
while(objReader.Read())
{
if(objReader.NodeType==XmlNodeType.Element)
{
element=objReader.Name;
如果(元素=“问题”)
{
测验=新测验();
dx=新列表();
IsLasteElement=true;
}
}
else if(objReader.NodeType==XmlNodeType.Text)
{
开关(元件)
{
案例“问题文本”:
quick.QuestionText=objReader.Value;
//Console.WriteLine(“问题文本:+objReader.Value”);
打破
案例“级别”:
quick.Level=objReader.Value;
//Console.WriteLine(“级别”+objReader.Value);
打破
案例“正确”:
Add(new Answers(){IsCorrect=true,AnswerName=objReader.Value});
//Console.WriteLine(“正确:”+objReader.Value);
打破
案例“不正确”:
Add(new Answers(){IsCorrect=false,AnswerName=objReader.Value});
//Console.WriteLine(“不正确:+objReader.Value”);
打破
}
}
if(IsLasteElement)
{
quick.AnswerList=dx;
测验。添加(测验);
IsLasteElement=false;
}
}
}
}
课堂测验
{
公共字符串文本;
公共字符串级别;
公共列表应答器列表;//lista de raspunsuri
}
公开课答案
{
公共领域是正确的;//raspuncul poate fi adevarat(真)sau false。
公共字符串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>

在Oracle SQL*PLUS中,functia LOWER(列/值)权限:
2.
fortarea Caractereleor scrise cu litere mari sau mixte,在caractere scrise cu litere mici中
FORTARE caracterelor scrise cu LITER mici在caractere scrise cu LITER maric中)
返回区(科隆那州文学中心)
翻译区lungimii Caracterelo dintr-o Colona/valoare la o lungime specificata
在Oracle SQL*PLUS中,functia INITCAP permite:
1.
在文学领域,文学领域的变革
转换区域primei Lite a fiecarui cuvant/litera mare中的Colonana
转换区域指定了一个未使用的cuvant、intr-o litera mare
在SQL*PLYS中,类似于SGBD和其他特定数据

当我按F5时,什么也没有发生。为什么?有人能帮我吗?谢谢!

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

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


如果您正在学习C#您会发现,编写Silverlight应用程序会将注意力从简单的学习语言转移到学习语言上来,因为Silverlight施加了额外的限制。

如前面的回答所述,您不能直接从Silverlight中的本地文件结构访问文件。您通常这样做的方式是o托管文件(在您的例子中是quick.xml)在web服务器上,让Silverlight调用web服务器来获取文件。您可以在承载Silverlight应用程序的同一web服务器上承载该文件。这是异步完成的,您可以在构造函数中启动此调用。另一件事是您读取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();      
               }
           }
        }         
    }