I'm having an issue to serialize an array in C# to be compliant with a XSD.
I need to serialize an array, where each property of each child would be listed into one single list, to be compliant with a XSD which define something like this:
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:element name="Id" type="xs:string"/>
<xs:element name="Value" type="xs:string"/>
</xs:sequence>
Exemple, I've got this:
<ServerRequest xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Time>11-08-15 08:27:31</Time>
<RequestContent>
<Id>myId1</Id>
<Value>myValue1</Value>
</RequestContent>
<RequestContent>
<Id>myId2</Id>
<Value>myValue2</Value>
</RequestContent>
</ServerRequest>
And what I need is this:
<ServerRequest xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Time>11-08-15 08:27:31</Time>
<Id>myId1</Id>
<Value>myValue1</Value>
<Id>myId2</Id>
<Value>myValue2</Value>
</ServerRequest>
Here is my code sample:
class Program
{
static void Main(string[] args)
{
ServerRequest test = new ServerRequest();
test.Time = DateTime.UtcNow.ToString();
test.RequestContent = new List<ServerRequestContent>()
{
new ServerRequestContent() { Id = "myId1", Value = "myValue1"},
new ServerRequestContent() { Id = "myId2", Value = "myValue2"}
};
using (StringWriter sw = new StringWriter())
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(ServerRequest));
xmlSerializer.Serialize(sw, test);
Console.WriteLine(sw.ToString());
}
}
}
[XmlRoot("ServerRequest")]
public class ServerRequest
{
[XmlElement()]
public string Time { get; set; }
[XmlElement]
public List<ServerRequestContent> RequestContent { get; set; }
}
public class ServerRequestContent
{
[XmlElement()]
public string Id { get; set; }
[XmlElement()]
public string Value { get; set; }
}
I've been trying for several hours, but still can't find a solution. Best thing I found so far is this: Serialize Array without root element, but I would have to change a lot of thing in the C# classes generated from the XSD, which I don't really want to.
Thanks for any help
Solution:
Implementing IXmlSerializable was probably the easiest way to deal with this. ServerRequest class now looks like this:
[XmlRoot("ServerRequest")]
public class ServerRequest : IXmlSerializable
{
[XmlElement()]
public string Time { get; set; }
[XmlElement]
public List<ServerRequestContent> RequestContent { get; set; }
#region IXmlSerializable
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
//...
}
public void WriteXml(XmlWriter writer)
{
writer.WriteElementString("Time", Time);
foreach (ServerRequestContent content in RequestContent)
{
writer.WriteElementString("Id", content.Id);
writer.WriteElementString("Value", content.Value);
}
}
#endregion
}