列入XML然后阅读XML

时间:2015-03-19 13:12:14

标签: c# xml xml-serialization xml-deserialization

到目前为止,我已经写了一个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");
        }

这是我试图读取和取消序列化的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中的列表,但我不确定是否有人可以提供帮助?

1 个答案:

答案 0 :(得分: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的经验,所以我不知道问题到底在哪里。