保存问题

时间:2016-10-27 15:40:35

标签: xml xamarin xamarin.ios xml-serialization question-answering

我正在为Xamarin iOS iPad App制作一个提问应用程序。 当有人打开应用程序时,这会显示类别,然后从类别中打开子类别,从子类别开始,这将打开一个问题列表。 打开问题时,它会显示一个详细信息页面,其中包含一个选项列表和一个用于添加问题答案的文本框。

现在问题是,当打开问题的详细页面并保存该特定问题的答案时。需要将列表中的答案和选择保存到针对该问题的XML文件中。

我怎么能做到这一点?

<?xml version="1.0" encoding="utf-16"?>
<Categories xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SubCategories>
    <Question QuestionTitle="I am question101" SubCategories="100" CategoryId="facilityId">
        <Checklists_Items Checklist_ItemTitle="title101" Checklist_ItemId="999" Checklist_ItemQuestion="question101" />
    </Question>
  </SubCategories>
</Categories>

1 个答案:

答案 0 :(得分:0)

我通过以下方式实现了这一目标: 创建一个包含保存值所需的所有必需属性的类文件,然后设置该类的属性值,并将值对象的类对象序列化为XML,并将该序列化XML字符串写入XML文件。

以下是对象类的示例代码。

using System;
using System.Collections.Generic;
using System.Xml.Serialization;

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[XmlTypeAttribute(AnonymousType = true)]
//[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]

public partial class QuestionsCollection
{
    private string _Question;
    private string _Answer;

    public QuestionsCollection()
    {
    }

    /// <remarks/>
    [XmlAttributeAttribute()]
    public string Question
    {
        get
        {
            return this._Question;
        }
        set
        {
            this._Question = value;
        }
    }

    /// <remarks/>
    [XmlArrayItemAttribute("Questions", IsNullable = false)]
    public string Answer
    {
        get
        {
            return this._Answer;
        }
        set
        {
            this._Answer = value;
        }
    }
}

序列化对象类的代码:

string question = "This is first question?";
string answer = "Answer to first question";

var path1 = Path.Combine(Directory, _path);
//Setting Values
            var c = new QuestionsCollection { Question = question, Answer = answer };

//Serialization of Object Class.    
            var s = new XmlSerializer(typeof(QuestionsCollection));
            var sb = new StringBuilder();

            using (var writer = new StringWriter(sb))
            {
                try
                {
                    s.Serialize(writer, c);
//Write Serialized String to file.
                    File.WriteAllText(path1, sb.ToString(), Encoding.UTF8);

                }
                catch (Exception e)
                {

                }
            }