如何编写我的XSD以便使用JAXB和XJC匹配所需的XML和Java格式

时间:2012-02-11 14:10:38

标签: java xsd jaxb code-generation xjc

  

可能重复:
  How generate XMLElementWrapper annotation with xjc and customized binding

我希望能够使用JAXB ...

处理这种格式的XML
<configuration>
  <!-- more content here -->
  <things>
    <thing>
      <name>xx1</name>
      <value>yy1</value>
    </thing>
    <thing>
      <name>xx2</name>
      <value>yy2</value>
    </thing>
  </things>
  <!-- more content here -->
</configuration>

我想将上述XML编组到这些Java类中(为简单起见,我留下了publicprotected以及getter / setter等修饰符:

class Configuration {
  List<Thing> things;
}

class Thing {
  String name;
  String value;
}

我目前的XSD结构的相关部分大致如下:

<complexType name="Configuration">
  <sequence>
    <!-- ... -->
    <element name="things" type="ns:Things" minOccurs="0" maxOccurs="unbounded"/>
    <!-- ... -->
  </sequence>
</complexType>

<complexType name="Things">
  <sequence>
    <element name="thing" type="ns:Thing" minOccurs="0" maxOccurs="unbounded"/>
  </sequence>
</complexType>

不幸的是,XJC也为Things生成了一个类,即使在处理的Java部分中确实没有必要。所以我的输出是:

class Configuration {
  Things things;
}

class Things {
  List<Thing> thing;
}

class Thing {
  String name;
  String value;
}

有什么方法可以告诉XJC避免产生这种不必要的课程?或者有什么方法可以重新说出我的XSD以避免这一代?这两种选择都适合我。

事实上,我想我需要生成@XmlElementWrapper注释,如下所示:

2 个答案:

答案 0 :(得分:1)

此问题中记录了一个可能的解决方案:

How generate XMLElementWrapper annotation with xjc and customized binding

这个XJC plugin允许生成以下Java代码,正是我所需要的(省略了无关的注释):

class Configuration {

  @XmlElementWrapper(name = "things")
  @XmlElement(name = "thing")
  List<Thing> things;
}

class Thing {
  String name;
  String value;
}

答案 1 :(得分:0)

您必须考虑到复杂类型大致转换为类。所以在您的XSD架构中,#34; Things&#34;复杂类型不是必需的。您的XSD应如下所示:

    <complexType name="Configuration">
    <sequence>
        <element name="things">
        <complexType>
            <sequence>
                <element name="thing" type="ns:Thing" minOccurs="0"
                    maxOccurs="unbounded" />
            </sequence>
            </complexType>F
        </element>
    </sequence>
    <!-- ... -->

</complexType>

<complexType name="Thing">
    <sequence>
        <element name="name" type="string" />
        <element name="value" type="string" />
    </sequence>
</complexType>