ValSmith
ValSmith

Reputation: 138

How to generate JAXB from xsd with maven using common classes

I am trying to parse .xml files that have the same structure but have different names. I am using maven to auto generate java classes from .xsd files to parse the xml files. I need to be able to auto generate most of the classes but use some pre created classes. This will allow me to extract some business logic and avoid duplication. Consider the two xml examples below:

<x>
    <y>
        <d attribute="value1"/>
    </y>
    <y>
        <d attribute="value2"/>
    </y>
</x>


<b>
    <c>
        <d attribute="value1"/>
    </c>
    <c>
       <d attribute="value2"/>
    </c>
</b>

The nodes "y" and "c" have identical structure but different names. I would like to be able to create a different class "W" that could be used to parse both xml files. Then when the Maven auto generation happens instead of creating the classes "Y" and "C" it will use my class "W" and apply it to both nodes. This can be accomplished manually by creating classes that have a structure similar to this:

public class x {
    @XmlType("y")
    private List<W> w;
}

public class W {
    private D d;
}

public class B {
    @XmlType("c")
    private List<W> w;
}

There are about 10 .xsd files each with 10k-20k lines so extending this example in the full case is not feasible. Any ideas? I would be open to other xml parsing frameworks if this functionality exits elsewhere.

Note: I tried using .xjb binding with an impl class. It expected the impl class to be a subtype of the generated class which was the opposite relationship I was looking for.

<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" jaxb:version="2.1"
               xmlns:xjc= "http://java.sun.com/xml/ns/jaxb/xjc"
               xmlns:xs="http://www.w3.org/2001/XMLSchema" >

    <jaxb:bindings schemaLocation="example.xsd" node="/xs:schema">
         <jaxb:bindings node="//xs:element[@name='y']">
           <jaxb:class implClass="W"/>
         </jaxb:bindings>
    </jaxb:bindings>
</jaxb:bindings>

Upvotes: 1

Views: 468

Answers (1)

lexicore
lexicore

Reputation: 43709

  • Define a complex type for your y and x elements.
  • Write your own implementation of this type (ex. com.acme.foo.W)
  • Use <jaxb:class ref="com.acme.foo.W"/> binding on this type to tell JAXB to use the W class instead of generating a new class.

See also:

JAXB: Prevent classes from being regenerated

Upvotes: 2

Related Questions