Reputation: 8156
Apologies on not being able to phrase the title more specifically but I can only explain by giving an example.
I'm trying to build a class that serializes to the following XML
<Customize>
<Content></Content>
<Content></Content>
<!-- i.e. a list of Content -->
<Command></Command>
<Command></Command>
<Command></Command>
<!-- i.e. a list of Command -->
</Customize>
My C# is:
[XmlRoot]
public Customize Customize { get; set; }
and
public class Customize
{
public List<Content> Content { get; set; }
public List<Command> Command { get; set; }
}
However, this produces (as it should), the following:
<Customize>
<Content>
<Content></Content>
<Content></Content>
</Content>
<Command>
<Command></Command>
<Command></Command>
<Command></Command>
</Command>
</Customize>
Are there some xml serialization attributes that would help achieve my desired xml, or do I have to find another way to write the class?
Upvotes: 0
Views: 91
Reputation: 125610
Use XmlElementAttribute
to mark your collection properties.
public class Customize
{
[XmlElement("Content")]
public List<Content> Content { get; set; }
[XmlElement("Command")]
public List<Command> Command { get; set; }
}
Quick test code:
var item = new Customize() { Content = new List<Content> { new Content(), new Content() }, Command = new List<Command> { new Command(), new Command(), new Command() } };
string result;
using (var writer = new StringWriter())
{
var serializer = new XmlSerializer(typeof(Customize));
serializer.Serialize(writer, item);
result = writer.ToString();
}
Prints:
<?xml version="1.0" encoding="utf-16"?>
<Customize xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Content />
<Content />
<Command />
<Command />
<Command />
</Customize>
Upvotes: 2
Reputation: 1750
public class Customize
{
[XmlElement("Content")]
public List<Content> Content { get; set; }
[XmlElement("Command")]
public List<Command> Command { get; set; }
}
Upvotes: 1