【问题标题】:How to write my XSD in order to match the desired XML and Java format using JAXB and XJC [duplicate]如何使用 JAXB 和 XJC 编写我的 XSD 以匹配所需的 XML 和 Java 格式 [重复]
【发布时间】:2012-03-03 16:37:57
【问题描述】:

可能重复:
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 注释:

【问题讨论】:

    标签: java xsd jaxb code-generation xjc


    【解决方案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;
    }
    

    【讨论】:

      【解决方案2】:

      您必须考虑到复杂类型大致转换为类。因此,在您的 XSD 架构中,“事物”复杂类型不是必需的。您的 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>
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-08
      • 2013-09-08
      • 2021-06-30
      相关资源
      最近更新 更多