Reputation: 155
I have created an ASP Web Service (.asmx), through which a request with an SQL query is sent and the table is returned. Since the table structure is not known, I thought to have a generic schema with the column name and value for each field, grouped in a row and then the table object. What I mean is this xml to be returned:
<table>
<row>
<field>
<colname>ID</colname>
<value>32</value>
</field>
<field>
...
</field>
</row>
<row>
...
</row>
</table>
and for this I created a table object, a row object, and a field object, like this:
public class Table
{
public Table()
{
Rows = new List<Row>();
}
public List<Row> Rows { get; set; }
}
public class Row
{
public Row()
{
Fields = new List<Field>();
}
public List<Field> Fields { get; set; }
}
public class Field
{
public string Name { get; set; }
public string Value { get; set; }
}
and then I created the methods, which retrieve the data from the DB, and map them to the table object, and this is then returned to the web method, which automatically serializes it and outputs the xml file like this:
<?xml version="1.0" encoding="utf-8"?>
<Table xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"...>
<Rows>
<Row>
<Fields>
<Field>
<Name>ID</Name>
<Value>23</Value>
</Field>
<Field>
...
</Field>
</Fields>
</Row>
<Row>
...
</Row>
</Rows>
</Table>
The problem is however, that I'm not getting the output with the structure I need, but also the variable names, like the tags 'Rows' and 'Fields', which are not needed.
I also tried having only the table object, without a Row object, but directly with List<List<Field>>
, but then the output structure is <Table><Row><ArrayOfFields><Field>...
So, in conclusion, how should I create a DTO, in this case the Table object, so that the xml output is as shown in the beginning, <Table><Row><Field>...
?
I hope I was somewhat clear in my question. Thanks in advance.
Upvotes: 2
Views: 1165
Reputation: 108
To do this, you need to apply custom serialization attributes to your classes and properties
For example
[System.Xml.Serialization.XmlRoot(ElementName = "table")]
public class Table
{
[System.Xml.Serialization.XmlElement("row")]
public Row[] Rows;
}
public class Row
{
public string V;
}
This will remove the extra elements. You can look under System.Xml.Serialization namespace to solve the other issues.
Upvotes: 2