【问题标题】:List into XML then Reading XML列出成 XML 然后读取 XML
【发布时间】:2015-03-19 13:12:13
【问题描述】:

到目前为止,我已经写了一个 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 的列表中的原因,但我不确定是否有人可以提供帮助?

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-04
      • 1970-01-01
      相关资源
      最近更新 更多