I need to create an object model for the following XML:
XML Example 1:
<InvoiceAdd> <TxnDate>2009-01-21</TxnDate> <RefNumber>1</RefNumber> <InvoiceLineAdd> </InvoiceLineAdd> </InvoiceAdd>
XML example 2:
<SalesOrderAdd> <TxnDate>2009-01-21</TxnDate> <RefNumber>1</RefNumber> <SalesOrderLineAdd> </SalesOrderLineAdd> </SalesOrderAdd>
XML output will be based on a single string parameter or enumeration. String txnType = "Invoice"; (or "SalesOrder");
I would use one TransactionAdd class:
@XmlRootElement public class TransactionAdd { public String txnDate; public String refNumber; private String txnType; ... public List<LineAdd> lines; }
instead of using subclasses or anything else. The code that creates the TransactionAdd instance is the same for both types of transactions; it differs only from the type.
This XML is used by the fairly well-known QuickBooks product and is used by the QuickBooks web service, so I cannot change the XML, but I want to simplify setting the element name based on the property (txnType).
I would consider something like a method to determine the name of a target element:
@XmlRootElement public class TransactionAdd { public String txnDate; public String refNumber; private String txnType; ... public List<LineAdd> lines; public String getElementName() { return txnType + "Add"; } }
Various transactions will be created using the following code:
t = new TransactionAdd(); t.txnDate = "2010-12-15"; t.refNumber = "123"; t.txnType = "Invoice";
The goal is to serialize the t object with the name of the top-level element based on txnType. For example:.
<InvoiceAdd> <TxnDate>2009-01-21</TxnDate> <RefNumber>1</RefNumber> </InvoiceAdd>
In the case of t.txnType = "SalesOrder", the result should be
<SalesOrderAdd> <TxnDate>2009-01-21</TxnDate> <RefNumber>1</RefNumber> </SalesOrderAdd>
Currently, I see only one workaround with subclasses of InvoiceAdd and SalesOrderAdd and using the @XmlElementRef annotation to have a name based on the class name. But he will need to instantiate different classes based on the type of transaction, and also have two other classes, InvoiceLineAdd and SalesOrderLineAdd, which look pretty ugly.
Please offer me some solution for this. I would think of something simple.