I'm writing a Web API 2 controller in MVC 5. At present, my XML output looks like this:
<ArrayOfVoucher xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MyAPI.Models">
<Voucher>
<VoucherDate>2018-04-04</VoucherDate>
<VoucherNumber>123</VoucherNumber>
<VoucherTransactions>
<VoucherTransaction>
<TransDate>2018-04-03</TransactionDate>
<TransType>GL</TransactionType>
</VoucherTransaction>
<VoucherTransaction>
<TransDate>2018-04-03</TransactionDate>
<TransType>GL</TransactionType>
</VoucherTransaction>
</VoucherTransactions>
<Voucher>
</ArrayOfVoucher>
However, the specification I'm working to states that it should look like this:
<ArrayOfVoucher xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MyAPI.Models">
<Voucher>
<VoucherDate>2018-04-04</VoucherDate>
<VoucherNumber>123</VoucherNumber>
<Transaction>
<TransDate>2018-04-03</TransactionDate>
<TransType>GL</TransactionType>
</Transaction>
<Transaction>
<TransDate>2018-04-03</TransactionDate>
<TransType>GL</TransactionType>
</Transaction>
<Voucher>
</ArrayOfVoucher>
Note the differences. In the second sample:
- The
VoucherTransaction
nodes are not grouped in together in a node called 'VoucherTransactions'. - The
VouncherTransaction
nodes are namedTransaction
.
The second one I can achieve by modifying the definition of my data model (see below), although I wonder if there's a better way, since the names of the model's properties at present are sensible.
My main question relates to that first point, though. How do I prevent the VoucherTransaction
nodes being grouped in a VoucherTransactions
node?
These are my data model classes:
Voucher
public class Voucher
{
public string VoucherNumber { get; set; }
public DateTime VoucherDate { get; set; }
public List<VoucherTransaction> VoucherTransactions { get; set; }
}
VoucherTransaction
public class VoucherTransaction
{
public string TransType { get; set; }
public DateTime TransDate { get; set; }
}
And the code currently creating the list is this:
foreach (SalesLedgerTransaction t in salesLedgerTransactions)
{
Voucher voucher = new Voucher
{
VoucherNo = "1",
VoucherDate = t.TransactionDate,
VoucherTransactions = new List<VoucherTransaction>()
};
VoucherTransaction arTransaction = new VoucherTransaction
{
TransType = "AR",
TransDate = t.TransactionDate
};
voucher.VoucherTransactions.Add(arTransaction);
VoucherTransaction glTransaction = new VoucherTransaction
{
TransType = "GL",
TransDate = t.TransactionDate
};
voucher.VoucherTransactions.Add(glTransaction);
vouchers.Add(voucher);
}
So yeah, if anyone can help me manipulate the XML so that the Voucher Transactions aren't grouped in a sub-node that'd be cool. Extra appreciation for help on specifying node names which differ from the models' properties (and the name of the root node - ArrayOfVoucher
isn't per the spec. either!).