【问题标题】:JAX-B - How to map a schema element to an existing Java class [duplicate]JAX-B - 如何将模式元素映射到现有的 Java 类 [重复]
【发布时间】:2012-10-16 19:29:10
【问题描述】:

可能重复:
jaxb xjc mapping to existing domain objects

我正在使用 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; }
}

我的架构:

<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>

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

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

【问题讨论】:

    标签: java jaxb


    【解决方案1】:

    您可以使用外部绑定文件来配置 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>
    

    XJC 通话

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

    【讨论】:

    • 谢谢布莱斯。看起来 ref 属性是使用 2.1 jxb 模式添加的,而我的 IDE 使用的是较旧的...所以我没有看到该选项!现在一切都很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多