Reputation: 1709
I want to bind the incoming XML to a JavaType
<?xml version="1.0" encoding="UTF-8"?>
<apiKeys uri="http://api-keys">
<apiKey uri="http://api-keys/1933"/>
<apiKey uri="http://api-keys/19334"/>
</apiKeys>
I wish to use JAXB, so I have defined an XSD. My XSD is incorrect, and the created objects - whilst being created - are empty.
My XSD:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="apiKeys" type="ApiKeysResponseInfo2" />
<xsd:complexType name="ApiKeysResponseInfo2">
<xsd:sequence>
<xsd:element name="uri" type="xsd:anyURI" minOccurs="1" maxOccurs="1">
</xsd:element>
<xsd:element name="apiKey" type="xsd:anyURI" minOccurs="1" maxOccurs="unbounded">
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
Obviously my element definitions are wrong. Any help much appreciated. Thanks.
Upvotes: 1
Views: 451
Reputation: 148977
I wish to use JAXB, so I have defined an XSD.
JAXB does not require an XML schema. We designed it to start from Java objects, the ability to generate an annotated model from an XML schema was added as a convenience mechanism.
I want to bind the incoming XML to a JavaType
You could use the object model below:
ApiKeys
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class ApiKeys {
private String uri;
private List<ApiKey> apiKey;
@XmlAttribute
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public List<ApiKey> getApiKey() {
return apiKey;
}
public void setApiKey(List<ApiKey> apiKey) {
this.apiKey = apiKey;
}
}
ApiKey
import javax.xml.bind.annotation.XmlAttribute;
public class ApiKey {
private String uri;
@XmlAttribute
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
}
Demo
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(ApiKeys.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum14643483/input.xml");
ApiKeys apiKeys = (ApiKeys) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(apiKeys, System.out);
}
}
Upvotes: 1