4

I have java class:

public class ActivityAddress {

    @XmlElement(name = "Elem1", required = false)
    private String elem1;

    @XmlElement(name = "Elem2", required = false)
    private String elem2;

    @XmlElement(name = "PostIndex", required = true)
    private String postIndex;
}   

I want to get schema like this:

<xs:complexType name="ActivityAddress">
<xs:sequence>
  <xs:choice minOccurs="0">
    <xs:element name="Elem1" type="xs:string"/>
    <xs:element name="Elem2" type="xs:string"/>
  </xs:choice>
  <xs:element name="PostIndex" type="xs:string"/>
</xs:sequence>

So the two fields "Elem1" and "Elem2" must be in choice.

Decision like this:

@XmlElements({
    @XmlElement(name = "Elem1", type = String.class, required = false),
    @XmlElement(name = "Elem2", type = String.class, required = false)
})
private String elem;

isn't suitable for me, because in java class i need have both fields.

Ноw i can do it? Can anyone please help?

1 Answers1

0

Generating an XML Schema

For the following Java class:

public class ActivityAddress {

    @XmlElement(name = "Elem1", required = false)
    private String elem1;

    @XmlElement(name = "Elem2", required = false)
    private String elem2;

    @XmlElement(name = "PostIndex", required = true)
    private String postIndex;
}   

You are going to get an XML Schema like the following, there isn't a way to generate the choice the way you would like.

<xs:sequence>
    <xs:element name="Elem1" type="xs:string" mincOccurs="0"/>
    <xs:element name="Elem2" type="xs:string" minOccurs="0"/> 
    <xs:element name="PostIndex" type="xs:string"/>
</xs:sequence>

Pointing to a Hand Crafted XML Schema

You can however generate an XML Schema and then modify it yourself and then tell JAXB to use it. This is done with the package level @XmlSchema annotation.

package-info.java

@XmlSchema(location="http://www.example.com/foo/mySchema.xsd")
package com.example.foo;
bdoughan
  • 147,609
  • 23
  • 300
  • 400