私は次のようにして、これを達成: そのクラスのプロパティ値を設定し、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)
{
}
}
使用モデルとバインディング –