IXmlSerializable を実装してカスタム xml シリアル化を作成したいと考えています。IXmlSerializable インターフェイスを実装するこのテスト クラスがあります。
[Serializable]
public class Employee : IXmlSerializable
{
public Employee()
{
Name = "Vyacheslav";
Age = 23;
}
public string Name{get; set;}
public int Age { get; set; }
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
this.Name = reader["Name"].ToString();
this.Age = Int32.Parse(reader["Age"].ToString());
}
public void WriteXml(XmlWriter writer)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.ConformanceLevel = ConformanceLevel.Fragment;
XmlWriter newWriter = XmlWriter.Create(writer, settings);
newWriter.WriteAttributeString("Name", this.Name);
newWriter.WriteAttributeString("Age", this.Age.ToString());
}
}
私がやりたいのは、xml宣言を省略することです。そのために、XmlWriterSettings の適切なインスタンスを作成し、それを 2 番目のパラメーターとして渡して、新しい XmlWriter を作成します。しかし、このコードをデバッグすると、newWriter.Settings.OmitXmlDeclaration が false に設定され、シリアル化されたデータにタグが含まれていることがわかります。私は何を間違っていますか?
実際のシリアル化は次のようになります。
var me = new Employee();
XmlSerializer serializer = new XmlSerializer(typeof(Employee));
TextWriter writer = new StreamWriter(@"D:\file.txt");
serializer.Serialize(writer, me);
writer.Close();
2 番目の質問は、シリアル化するフィールドにカスタム型 ContactInfo を持つ型 Employee をシリアル化する場合、ContactInfo にも IXmlSerializable を実装する必要があるかどうかです。