Unmarshal Go struct List to XML without creating a nested structure

Hello, I have faced a problem about creating a go struct that when unmarshalled can match the below xml structure. The problem is in PAYMENTS part. Say payment struct has a field named PMTTYPE and PMTAMOUNT how can you unmarshal a list of PAYMENTS and have them nested like below without creating a nested structure.

<TOTALS>
			<TOTALTAXEXCL>169.49</TOTALTAXEXCL>
			<!-- Total of all the items exclusive of Tax-->
			<TOTALTAXINCL>200</TOTALTAXINCL>
			<!-- Total of all the items inclusive of Tax-->
			<DISCOUNT>0.00</DISCOUNT>
		</TOTALS>
		<PAYMENTS>
			<PMTTYPE>CASH</PMTTYPE>
			<!-- Mode of Payment can either be CASH, CHEQUE, EMONEY or CCARD if receipt is generated. In this case payment is already received-->
			<PMTAMOUNT>200.00</PMTAMOUNT>
			<!-- Payment amount-->
			<PMTTYPE>INVOICE</PMTTYPE>
			<!-- Mode of Payment can only be INVOICE if invoice is generated. In this case payment is not yet received that is why we use Invoice -->
			<PMTAMOUNT>200.00</PMTAMOUNT>
			<!-- Payment amount-->
		</PAYMENTS>
		<VATTOTALS>
			<VATRATE>A</VATRATE>
			<!-- Tax group applicable on the items for VAT items should A and for no VAT items should be C-->
			<NETTAMOUNT>169.49</NETTAMOUNT>
			<!-- Total of all the items exclusive of Tax-->
			<TAXAMOUNT>30.51</TAXAMOUNT>
			<!-- Tax amount paid-->
		</VATTOTALS>

You mean like this? Go Playground - The Go Programming Language

Thanks for that attempts. I meant turning a go struct into XML like the one above. The expectation is having PMTTYPE followed by PMTAMOUNT then PMTTYPE followed by PMTAMOUNT as a list

Ah, I see. Going from code to an encoding (e.g. to XML or to JSON, etc.) is called “marshaling.” Unmarshaling is when you convert from XML (or JSON, etc.) to structs (or whatever other data type you are deserializing from).

If you want the code that will produce that XML, I think you want this:

If you have fields other than just two (PMTTYPE and PMTAMOUNT), I might have a different idea, but I think this is the most straightforward for just these two types.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.