2015-03-19 54 views
0

到目前爲止,我已經寫了一個XML存儲列表,並通過將其通過構造函數並將其保存爲這樣一些其他有價值的信息:列表轉換成XML,然後讀取XML

RoundEdit._quizStruct.Add(new RoundEdit(quizId, roundId, roundName, QuestionsCount, Questions)); 

這是建設者和什麼不。

public RoundEdit() 
     { 
      quizStruct = new List<RoundEdit>(); 
     } 
     public RoundEdit(int inQuizID, int inRoundId,string inRoundName, int inNumOfQuestions, List<int> inRoundQuestions) 
     { 
      QuizId = inQuizID; 
      RoundId = inRoundId; 
      roundName = inRoundName; 
      numOfQuestions = inNumOfQuestions; 
      roundQuestions = inRoundQuestions; 

     } 

     public static void saveRounds() 
     { 
      SaveXmlQuiz.SaveData(_quizStruct, "rounds.xml"); 
     } 

這是我試圖讀取和de序列化的xml文件。

<?xml version="1.0" encoding="utf-8"?> 
<ArrayOfRoundEdit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <RoundEdit> 
    <_quizId>0</_quizId> 
    <_roundId>1</_roundId> 
    <_roundName>1</_roundName> 
    <_numOfQuestions>2</_numOfQuestions> 
    <_roundQuestions> 
     <int>2</int> 
     <int>3</int> 
    </_roundQuestions> 
    </RoundEdit> 
    <RoundEdit> 
    <_quizId>0</_quizId> 
    <_roundId>2</_roundId> 
    <_roundName>2</_roundName> 
    <_numOfQuestions>2</_numOfQuestions> 
    <_roundQuestions> 
     <int>2</int> 
     <int>3</int> 
    </_roundQuestions> 
    </RoundEdit> 
</ArrayOfRoundEdit> 

,但是當我用這個方法

XmlSerializer xs; FileStream read; RoundEdit info; 
      xs = new XmlSerializer(typeof(RoundEdit)); 
      read = new FileStream("rounds.xml", FileMode.Open, FileAccess.Read, FileShare.Read); 
      try 
      { 
       info = (RoundEdit)xs.Deserialize(read);//exception here for john to look at 
       RoundList.Add(new RoundEdit(info._quizId, info._roundId, info._roundName, info._numOfQuestions, info._roundQuestions)); 
      } 

我得到錯誤的有XML文檔中的錯誤(2,2),我認爲這是它是如何在閱讀事業列表中存儲的roundQuestions,但我不確定是否有人可以提供幫助?

回答

0

,我建議你使用XDocument類是這樣的:

var xDoc = XDocument.Load(filepath); 
var roundEditXmlArr = xDoc.Element("ArrayOfRoundEdit").Elements("RoundEdit").ToArray(); // array or list but you know the exact number 

現在,你必須在它您需要的元素的數組。現在你可以讀出這些物品的信息:

List<RoundEdit> roundEditList = new List<RoundEdit>(); 

for (var i = 0; i < roundEditXmlArr.Length; i++) 
{ 
    var roundEdit = new RoundEdit(roundEditXmlArr[i].Element("_quizId").Value, [...]); 
    roundEditList.Add(roundEdit); 
} 

這段代碼僅僅是一個例子 - 執行肯定會更好,應該是。

對不起,我沒有XmlSerializer的經驗,所以我不能說問題在哪裏。