在不同的XML/根元素中使用JAXB共享子元素的类

4

在使用JAXB时,通过xjc从xsd模式自动生成类时。

alpha.xsd

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="alpha">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="persons">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="person" maxOccurs="unbounded" minOccurs="0">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element type="xs:string" name="name"/>
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

beta.xml

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="country">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="class">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="person">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element type="xs:string" name="name"/>
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

如您所见,这里有一个共享在这两个方案中的“Person”元素。我想做的是:
  • 使用xjc生成类,使得“ObjectFactory”类为两个模式类所共享(输出类将在一个包中)
  • 不使用嵌套静态类(带有属性“localScoping =“toplevel””)
  • 使用“Person”类来绑定“/alpha/persons/person”和“/country/class/person”,因此不会创建两个“Person”类
这样做的目的是将一个xml取消编组,应用业务逻辑并创建另一个作为输出,其中一些元素(如“Person”)相同且共享于两个xml文件。命名空间对于两个文件将是相同的。
如果您可以向我提供完整的.xjb绑定设置文件,我将不胜感激。到目前为止,我的仅包含:
<jxb:bindings version="1.0" 
  xmlns:jxb="http://java.sun.com/xml/ns/jaxb" 
  xmlns:xs="http://www.w3.org/2001/XMLSchema" 
  xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" 
  jxb:extensionBindingPrefixes="xjc">

  <jxb:globalBindings localScoping="toplevel"/>
</jxb:bindings>

当然,我遇到了名称冲突错误,因为我不知道如何设置绑定编译器,以使其将“Person”视为相同的实体/元素。
2个回答

6

您可以使用外部绑定文件来指示在类生成期间,我们希望使用现有的类作为名为Document的复杂类型。

binding.xml

<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="beta.xsd">
        <jxb:bindings node="//xs:element[@name='person']/complexType">
            <jxb:class ref="alpha.Person"/>
        </jxb:bindings>
    </jxb:bindings>
</jxb:bindings>

XJC调用

xjc -b binding.xml beta.xsd

1
如果A中的person的命名空间等于Bperson的命名空间,则xjc将生成正确的类。请注意,要保留namespaceperson的HTML标签。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接