他のクラスに変数として含まれているクラスがあり、他のクラスと一緒に XML としてシリアル化する必要があります。一部のクラスでは属性として含まれ、残りは要素になります。を使用してこれを処理する簡単な方法はありますかXMLSerializer
。
これを明確にするために、ここに例を示します。私はクラスを持っていますB
:
public class B {
public string name { get; set; }
public string description { get; set; }
public B() { }
public B(string name, string description) {
this.name = name;
this.description = description;
}
}
次にクラスA
:
public class A {
[XmlAttribute("aName")]
public string name { get; set; }
[XmlAttribute("bName")]
public B b { get; set; }
public A() { }
public A (string name, B b){
this.name = name;
this.b = b;
}
}
それをシリアル化するには、次のようにします。
XmlSerializer serializer = new XmlSerializer(typeof(A));
TextWriter textWriter = new StreamWriter(@"C:\Test.xml");
serializer.Serialize(textWriter, new A("A Name", new B("B Name", "B Description")));
textWriter.Close();
A
クラスを次のように変更できることはわかっています。
public class A {
[XmlAttribute("aName")]
public string name { get; set; }
[XmlIgnore]
public B b { get; set; }
[XmlAttribute("bName")]
public string bXml {get{return b==null ? null : b.name;} set{this.b = new B(value, null);}}
public A() { }
public A (string name, B b){
this.name = name;
this.b = b;
}
}
しかし、これは複数の場所で発生するためbXML
、要素としてではなく属性として使用したいすべてのクラスに を追加する必要がなくなると便利です。B
これが必要なときにコンバーターを設定する方法、または Class for asAttribute
andにコードを追加する方法があることを望んでいましたasElement
。