attributes を使用して xml シリアライゼーションを制御できます。属性を使用XmlAttribute
して、要素としてのデフォルトのシリアル化を属性としてのシリアル化に変更します。属性を使用XmlElement
して、リストを xml 要素のフラット シーケンスとしてシリアル化します。
public class Product
{
public Cycle Cycle { get; set; }
public Brand Brand { get; set; }
public List<Item> Updates { get; set; }
}
public class Cycle
{
[XmlAttribute("Type")]
public string Type { get; set; }
}
public class Brand
{
[XmlAttribute("Type")]
public string Type { get; set; }
[XmlAttribute("Include")]
public string Include { get; set; }
}
public class Item
{
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlElement("Artifact")]
public List<Artifact> Artifacts { get; set; }
}
public class Artifact
{
[XmlAttribute("Kind")]
public int Kind { get; set; }
[XmlAttribute("Action")]
public int Action { get; set; }
}
シリアライゼーション:
Product p = new Product()
{
Cycle = new Cycle() { Type = "x0446" },
Brand = new Brand() { Type = "z773g", Include = "All" },
Updates = new List<Item>()
{
new Item() { Name = "Foo",
Artifacts = new List<Artifact>() {
new Artifact() { Action = 3, Kind = 6 }
}
},
new Item() { Name = "Bar",
Artifacts = new List<Artifact>() {
new Artifact() { Action = 3, Kind = 6 },
new Artifact() { Action = 3, Kind = 53 },
}
}
}
};
XmlSerializer serializer = new XmlSerializer(typeof(Product));
Stream stream = new MemoryStream(); // use whatever you need
serializer.Serialize(stream, p);
結果:
<Product>
<Cycle Type = "x0446" />
<Brand Type = "z773g" Include="All" />
<Updates>
<Item Name = "Foo">
<Artifact Kind="6" Action="3" />
</Item>
<Item Name = "Bar">
<Artifact Kind="6" Action="3" />
<Artifact Kind="53" Action="3" />
</Item>
</Updates>
</Product>