繁体   English   中英

列出为XML然后读取XML

[英]List into XML then Reading 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");
        }

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

我建议您像这样使用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经验,所以我不能说问题出在哪里。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM