Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
712 views
in Technique[技术] by (71.8m points)

xml - JAXB xjc mapping to existing domain objects

I have done a lot of searching and cannot find a concise example of how to map an XML schema to existing domain objects instead of creating brand new ones utilizing xjc. I have created a bindings (xjb) file but still can find no way of accomplishing this.

If I have an existing domain Object that I want JAXB to use such as the following:

package com.blah.domain;
class CustomerOffice{
   private int id;
   private String name;
   private String phone;
}

And I have an XML Schema like the following:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:www="http://www.blah.com" 
xmlns:xs="http://www.w3.org/2001/XMLSchema" 
targetNamespace="http://www.blah.com" elementFormDefault="unqualified">
   <xs:element name="Customer">
      <xs:complexType>
         <xs:sequence>
           <xs:element name="id" type="xs:int" nillable="false" minOccurs="1" maxOccurs="1"/>
           <xs:element name="name" type="xs:string"/>
           <xs:element name="city" type="xs:string"/>
           <xs:element name="CustomerOffice" type="www:CustomerOffice" maxOccurs="unbounded"/>
        </xs:sequence>
     </xs:complexType>
   </xs:element>
   <xs:complexType name="CustomerOffice">
      <xs:sequence>
        <xs:element name="name" type="xs:string"/>
        <xs:element name="length" type="xs:int"/>
      </xs:sequence>
   </xs:complexType>
</xs:schema>

If I go to generate the JAXB classes with xjc it will create a new class called Customer (which I want). It will also create a new class called CustomerOffice (which I don't want, I want it to use my existing domain object).

So instead of the schema pointing to "type:www:CustomerOffice" I would want it to use the existing com.blah.domain.CustomerOffice.

I tried to make this as simple an example as possible, any help is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use an external binding file to configure XJC to do what you want.

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

    <jxb:bindings schemaLocation="yourSchema.xsd">
        <jxb:bindings node="//xs:complexType[@name='CustomerOffice']">
            <jxb:class ref="com.blah.domain.CustomerOffice"/>
        </jxb:bindings>
    </jxb:bindings>
</jxb:bindings>

XJC Call

xjc -d outputDir -b binding.xml yourSchema.xsd

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...