Eddy
Eddy

Reputation: 35

Detect XML 'schema' in java

I use JAXB to unmarshal an XML message (string) to a POJO. Now it is possible to receive different kinds of messages. Each kind of message has a different structure and maps to a different POJO.

e.g. PaymentRequest contains an amount and currency, PrintRequest contains a text and a logo

<PaymentRequest>
  <amount>1.0</amount>
  <currency>EUR</currency>
</PaymentRequest>

<PrintRequest>
  <text>Hello world!</text>
  <logo>stackoverflow.png</logo>
</PrintRequest>

What is the best way or best practice to identify which kind of message I have received?

Any pointers are appreciated.

Upvotes: 0

Views: 513

Answers (1)

lexicore
lexicore

Reputation: 43651

Why don't you just unmarshal and then check the type of the unmarshalled message?

You may need to construct a JAXBContext with several packages for this to work. Something like:

JAXBContext context = JAXBContext.newInstance("com.acme.foo.payment:com.acme.foo.print");

The context must know the elements you (potentially) want to unmarshal.

Next, in you schemas you may also use substitution groups in your schema. Since both PrintRequest and PaymentRequests are requests, you may want to define an abstract element for them:

<xs:element name="AbstractRequest" type="base:AbstractRequestType" abstract="true"/>

Then your PrintRequest and PaymentRequest may substitute this element:

<xs:element name="PaymentRequest" type="payment:PaymentRequestType" substititionGroup="base:AbstractRequest"/>

In your request/response schema you can use the AbstractRequest then which can be substituted by PaymentRequest. This will give you somewhat more type safety when unmarshalling. You'll know you'll get a JAXBElement<? extends AbstractRequestType and will only have to figure out, which of the request types that is. This can be done based on the QName of the JAXBElement or brute-force with instanceof. A finer approach would be to use a visitor pattern for this, but it's a bit more complicated to condigure.

Upvotes: 1

Related Questions