Paul
Paul

Reputation: 3954

XMLSerializer for Array of Objects

I have the following XML:

<SQLToData>
  <PreProcessors>
    <PreProcessor>
      <Name>Input1</Name>
      <Expression>1 == a</Expression>
    </PreProcessor>
  </PreProcessors>
  <DataSource>
    <Type>SQLServer</Type>
    <ConnectionString>Data Source=****</ConnectionString>
  </DataSource>
  <SQL>
    SELECT * FROM TABLE
  </SQL>
  <ReturnType>DataTable</ReturnType>
</SQLToData>

And the following C# classes:

public class SQLToData
{
    public SQLToDataDataSource DataSource { get; set; }
    [XmlArray("PreProcessors")]
    public SQLToDataPreProcessor[] PreProcessors { get; set; }
    public string SQL { get; set; }
    public string ReturnType { get; set; }
}

[XmlRoot("DataSource")]
public class SQLToDataDataSource
{
    public string Type { get; set; }
    public string ConnectionString { get; set; }
}

[XmlRoot("PreProcessor")]
public class SQLToDataPreProcessor
{
    public string Name { get; set; }
    public string Expression { get; set; }
}

I call the Serializer like this:

XDocument xml = XDocument.Load(xmlPath);

XmlSerializer inputSerializer = new XmlSerializer(typeof(SQLToData));
XElement xmlElement = xml.XPathSelectElement("/SQLToData");

SQLToData config;
using (TextReader reader = new StringReader(xmlElement.ToString()))
{
    config = (SQLToData)inputSerializer.Deserialize(reader);
}

However, I'm not getting the data in the Array for PreProcessors.

What do I have wrong in my configuration?

Upvotes: 0

Views: 41

Answers (1)

Paul
Paul

Reputation: 3954

Found the issue. I was missing XmlArrayItem tag.

public class SQLToData
{
    public SQLToDataDataSource DataSource { get; set; }
    [XmlArray("PreProcessors")]
    [XmlArrayItem("PreProcessor")]
    public SQLToDataPreProcessor[] PreProcessors { get; set; }
    public string SQL { get; set; }
    public string ReturnType { get; set; }
}

Upvotes: 1

Related Questions