您可以使用属性控制 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>