我通过执行以下操作实现了这一点:使用保存值所需的所有必需属性创建一个类文件,然后设置该类的属性值并将具有值的类对象序列化为 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)
{
}
}