JAX-B - 如何将架构元素映射到现有Java类

Jen*_* S. 5 java jaxb

可能重复:
jaxb xjc映射到现有域对象

我正在使用JAX-B从XML模式生成Java类.

我的架构中有一个元素,我想绑定到我的项目中存在的Java类.我的绑定是在.xjb文件中完成的.我已经尝试了几种方法,但无法获得任何工作.

这可能吗?如果是这样,怎么样?

这是我的问题的一个较小的例子:

我的现有Java类:

package com.existing; 

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
public class Existing {
    private String prop; 
    public String getProp() { return prop; }
    public void setProp(String prop) { this.prop = prop; }
}
Run Code Online (Sandbox Code Playgroud)

我的架构:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
     targetNamespace="http://www.baloiselife.com/xpression/policy"
     xmlns="http://www.baloiselife.com/xpression/policy" >

<xs:element name="root_node">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="some_other_propery" type="xs:string"/>
      <!-- I want this element to map onto my existing Java class -->
      <xs:element name="special_element" type="existing_type" minOccurs="0" />
    </xs:sequence>
  </xs:complexType>
</xs:element>

<!-- I want this element to be ignored, and instead my Java class used -->
<xs:complexType name="existing_type">
  <xs:sequence>
    <xs:element name="prop" type="xs:string" minOccurs="0" />
  </xs:sequence>
</xs:complexType>
Run Code Online (Sandbox Code Playgroud)

那么任何想法我的约束应该是什么?我尝试使用jxb:class设置,但无法使其工作.我的最终结果有两个要求:

  1. 从架构生成ExistingType类
  2. RootNode类有一个Existing类型的元素,它映射到我现有的Java类

bdo*_*han 7

您可以使用外部绑定文件将XJC配置为执行您想要的操作.

binding.xjb

<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='existing_type']">
            <jxb:class ref="com.existing.Existing"/>
        </jxb:bindings>
    </jxb:bindings>
</jxb:bindings>
Run Code Online (Sandbox Code Playgroud)

XJC电话

xjc -d outputDir -b binding.xjb yourSchema.xsd
Run Code Online (Sandbox Code Playgroud)