I need to create the following XML and want to create it via XmlSerialization so the data itself can be generated dynamically via objects.
<chart>
<series>
<value xid="0">Not Submitted: 20</value>
<value xid="1">Submitted: 11</value>
<value xid="2">Rejected: 2</value>
</series>
<graphs>
<graph gid="0">
<value xid="0" color="#FF0000">20</value>
<value xid="1" color="#00FF00">11</value>
<value xid="2" color="#0000FF">2</value>
</graph>
<graph gid="1">
<value xid="0" color="#FF0000">24</value>
<value xid="1" color="#00FF00">7</value>
<value xid="2" color="#0000FF">4</value>
</graph>
</graphs>
</chart>
I originally came up with this but it doesn’t completely work (in fact, some of it is just plain wrong). Any ideas?
// the //chart/series/value elements with attributes
internal class BarChartSeriesValue
{
[XmlAttribute(AttributeName = "xid")]
public int Xid { get; set; }
[XmlText]
public int Value { get; set; }
}
// the //chart/graphs/graph/value elements with attributes
internal class BarChartGraphValue
{
[XmlAttribute(AttributeName = "xid")]
public int Xid { get; set; }
[XmlAttribute(AttributeName = "color")]
public string Color { get; set; }
[XmlText]
public int Value { get; set; }
}
// the //chart/series collection of values
internal class BarChartSeries : List<BarChartSeriesValue>
{
[XmlElement(ElementName = "series")]
public List<BarChartSeriesValue> Series { get; set; }
}
// the //chart/graphs/graph collection of values
internal class BarChartGraph : List<BarChartGraphValue>
{
[XmlAttribute(AttributeName = "gid")]
public int GraphId { get; set; }
}
// the //chart/graphs collection of graph elements
internal class BarChartData
{
[XmlElement(ElementName = "series")]
public BarChartSeries Series { get; set; }
[XmlElement(ElementName = "graphs")]
public BarChartGraph Graphs { get; set; }
}
EDIT – 8/22 11:24pm PST
When I said it was just plain wrong, all I had to do was look at it and realize that the data structures wouldn’t map to the desired XML. The part that was really throwing me was the nested graphs structure.
I previously did not know about generating classes from XML via the XSD. It looks very useful and helpful.
Thanks to all who provided solutions
Here is a quick project.
I use this class or a variant of it:
Generic XML Serializer Class for C# and an XML Serialization usage example
Then here is the code you need.
Here is how to use it.