In my XML I have
<myelem required="false"/>
How I can read the required attribute as a boolean? I can read it as String and inside a getter do this: return new Boolean(required)
But maybe there are some more elegant ways?
Just simply use boolean for the member in your Java class:
#XmlAttribute
private boolean required;
Or, if you use getter-setter style of mapping:
#XmlAttribute
public boolean isRequired() {
return required;
}
The JAXB unmarshaller is able to interpret "true" and "false" strings in the XML document as boolean value.
UPDATE:
I tested this with the following classes:
test/MyElem.java:
package test;
import javax.xml.bind.annotation.*;
#XmlRootElement(name="myelem")
public class MyElem {
private boolean required;
#XmlAttribute
public boolean isRequired() {
return required;
}
public void setRequired(boolean value) {
required = value;
}
}
Test.java:
import javax.xml.bind.*;
import java.io.*;
import test.*;
public class Test {
public static void main(String[] args) {
try {
JAXBContext jc = JAXBContext.newInstance(MyElem.class);
Unmarshaller u = jc.createUnmarshaller();
Object o = u.unmarshal( new File( "test.xml" ) );
System.out.println(((MyElem)o).isRequired());
} catch(Exception e) {
e.printStackTrace();
}
}
}
And with the following input (test.xml):
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<myelem required="true"/>
I get the correct result on the console:
true
Related
Having issues reading the following XML file that I create.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<prsettings>
<prsetting>
<players>
<player>
<lastDateEntered>0</lastDateEntered>
<lastTournament>1</lastTournament>
<playerId>0</playerId>
<playersStatus>unrated</playersStatus>
<playersTag>asfd</playersTag>
<score>5.0</score>
<setsPlayed>0</setsPlayed>
<tourneysWhileInactive>0</tourneysWhileInactive>
</player>
<player>
<lastDateEntered>0</lastDateEntered>
<lastTournament>1</lastTournament>
<playerId>1</playerId>
<playersStatus>unrated</playersStatus>
<playersTag>ba</playersTag>
<score>5.0</score>
<setsPlayed>0</setsPlayed>
<tourneysWhileInactive>0</tourneysWhileInactive>
</player>
<player>
<lastDateEntered>0</lastDateEntered>
<lastTournament>1</lastTournament>
<playerId>2</playerId>
<playersStatus>unrated</playersStatus>
<playersTag>asdgf</playersTag>
<score>5.0</score>
<setsPlayed>0</setsPlayed>
<tourneysWhileInactive>0</tourneysWhileInactive>
</player>
</players>
<challongeApiKey>asbg</challongeApiKey>
<challongeUsername>asf</challongeUsername>
<implementPointDecay>false</implementPointDecay>
<numSetsNeeded>5</numSetsNeeded>
<numTourneysForActive>2</numTourneysForActive>
<numTourneysForInnactive>5</numTourneysForInnactive>
<numTourneysNeeded>5</numTourneysNeeded>
<pointsRemoved>5</pointsRemoved>
<prName>asf</prName>
<removeInnactive>false</removeInnactive>
<showPlacingDiff>false</showPlacingDiff>
<showPointDiff>false</showPointDiff>
<startOfDecay>3</startOfDecay>
</prsetting>
I have an observableList of PRSetting objects and within the PRSetting objects I have an ArrayList of Players. This is why I created a POJO file and within the PRSetting Object the only object I set up was the following.
#XmlElementWrapper(name="players")
#XmlElement(name ="player")
private ArrayList<PlayerProfile> playersList = new ArrayList<PlayerProfile>();
Here is also my POJO file that is supposed to be used to write and read the XML file.
#XmlRootElement (name = "prsettings")
public class PRSettingsWrapper {
private ObservableList<PRSettings> prList;
#XmlElement(name = "prsetting")
public ObservableList<PRSettings> getPrList(){
return prList;
}
public void setPrList(ObservableList<PRSettings> prList){
this.prList = prList;
}
}
For some reason whenever I attempt to to load the data with the following code
JAXBContext context = JAXBContext
.newInstance(PRSettingsWrapper.class);
Unmarshaller um = context.createUnmarshaller();
// Reading XML from the file and unmarshalling.
PRSettingsData wrapper = (PRSettingsData) um.unmarshal(file);
prList.clear();
prList.addAll(wrapper.getPrList());
// Save the file path to the registry.
setPrSettingsFilePath(file);
I cannot seem to successfully load the xml files into the objects. The file path is working correctly, but I'm not sure what I'm doing wrong.
Thank you in advance for your help.
Sorry to mislead you about the cause.
The problem is caused by ObservableList;
You can refer to this article:
Marshalling ObservableList with JAXB
I modified code from the link above, and the followings should be workable.
anotherTest.MyContainer
package anotherTest;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "prsettings")
public class MyContainer extends MyObject {
private ObservableList<MyObject> children = FXCollections.observableArrayList();
#XmlElements({ #XmlElement(name = "prsetting", type = MyObject.class) })
public List<MyObject> getChildren() {
return children;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("children:");
for (MyObject node : children) {
sb.append("\n");
sb.append(" " + node.toString());
}
return sb.toString();
}
}
anotherTest.MyObject
package anotherTest;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlType;
#XmlType(name = "Object")
public class MyObject {
private String challongeApiKey;
#XmlElementWrapper(name = "players")
private List<PlayerProfile> player;
public String getChallongeApiKey() {
return challongeApiKey;
}
public void setChallongeApiKey(String challongeApiKey) {
this.challongeApiKey = challongeApiKey;
}
public List<PlayerProfile> getPlayer() {
return player;
}
public void setPlayers(List<PlayerProfile> player) {
this.player = player;
}
}
anotherTest.PlayerProfile
package anotherTest;
public class PlayerProfile {
private int playerId;
private String playersStatus;
public int getPlayerId() {
return playerId;
}
public void setPlayerId(int playerId) {
this.playerId = playerId;
}
public String getPlayersStatus() {
return playersStatus;
}
public void setPlayersStatus(String playersStatus) {
this.playersStatus = playersStatus;
}
}
anotherTest.Example
package anotherTest;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class Example {
public static void main(String[] args) {
// create container with list
MyContainer container = new MyContainer();
// add objects
MyObject object;
object = new MyObject();
object.setChallongeApiKey("ABCABC");
container.getChildren().add(object);
PlayerProfile p = new PlayerProfile();
p.setPlayerId(1);
p.setPlayersStatus("unrated");
List<PlayerProfile> l = new ArrayList<>();
l.add(0, p);
object.setPlayers(l);
// marshal
String baseXml = marshal(container);
// unmarshal
container = unmarshal(baseXml);
System.out.println("unmarshal test: " + container.getChildren().get(0).getChallongeApiKey());
System.out.println("unmarshal test: " + container.getChildren().get(0).getPlayer().get(0).getPlayerId());
System.out.println("unmarshal test: " + container.getChildren().get(0).getPlayer().get(0).getPlayersStatus());
System.exit(0);
}
public static String marshal(MyContainer base) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(MyContainer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter stringWriter = new StringWriter();
jaxbMarshaller.marshal(base, stringWriter);
String xml = stringWriter.toString();
System.out.println("XML:\n" + xml);
return xml;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static MyContainer unmarshal(String xml) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(MyContainer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
StringReader stringReader = new StringReader(xml);
MyContainer container = (MyContainer) jaxbUnmarshaller.unmarshal(stringReader);
return container;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
the output in the console is
XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<prsettings>
<prsetting>
<players>
<player>
<playerId>1</playerId>
<playersStatus>unrated</playersStatus>
</player>
</players>
<challongeApiKey>ABCABC</challongeApiKey>
</prsetting>
</prsettings>
unmarshal test: ABCABC
unmarshal test: 1
unmarshal test: unrated
Sorry, I don't know why either. I tested that if declare children to List<MyObject>, it can work properly. However, when it comes to ObservableList, you must declare it like this, or NullPointerException will occur when unmarshalling (but the same code works well on marshalling).
private ObservableList<MyObject> children = FXCollections.observableArrayList();
it this a bug?
I need nillable = "true" in my xsd schema. The only way to generate such an element from my java code is to use #XmlElement(nillable = true), right? But in this case, I will not be able to take advantage of this definition, I will not be able to check if the element is set to nil. The method isNil() is in the JAXBElement wrapper class.
So, what are my options here - I want to generate nillable = "true" in my xsd schema AND be able to check if it is set from my java code.
I need nillable = "true" in my xsd schema. The only way to generate
such an element from my java code is to use #XmlElement(nillable =
true), right?
Yes.
But in this case, I will not be able to take advantage of this
definition, I will not be able to check if the element is set to nil.
The method isNil() is in the JAXBElement wrapper class.
You can do getFoo() == null to determine if it was null. If you are trying to determine if the null corresponds to an absent element or xsi:nil="true" then you will have to do more. A set won't be done for absent nodes so you can put logic in your setter to track if a set to null was done because of an element with xsi:nil="true.
#XmlElement(nillable=true)
public String getFooString() {
return fooString;
}
public void setFooString(String foo) {
this.fooString = foo;
this.setFoo = true;
}
If you don't want to have this extra logic (which doesn't help for marshalling anyways you need to leverage JAXBElement.
#XmlElementRef(name="fooJAXBElement")
public JAXBElement<String> getFooJAXBElement() {
return fooJAXBElement;
}
public void setFooJAXBElement(JAXBElement<String> fooJAXBElement) {
this.fooJAXBElement = fooJAXBElement;
}
Java Model
Root
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
#XmlRootElement
#XmlType(propOrder={"fooString", "barString", "fooJAXBElement", "barJAXBElement"})
public class Root {
private String fooString;
private String barString;
private JAXBElement<String> fooJAXBElement;
private JAXBElement<String> barJAXBElement;
private boolean setFoo;
private boolean setBar;
#XmlElement(nillable=true)
public String getFooString() {
return fooString;
}
public void setFooString(String foo) {
this.fooString = foo;
this.setFoo = true;
}
public boolean isSetFooString() {
return setFoo;
}
#XmlElement(nillable=true)
public String getBarString() {
return barString;
}
public void setBarString(String bar) {
this.barString = bar;
this.setBar = true;
}
public boolean isSetBarString() {
return setBar;
}
#XmlElementRef(name="fooJAXBElement")
public JAXBElement<String> getFooJAXBElement() {
return fooJAXBElement;
}
public void setFooJAXBElement(JAXBElement<String> fooJAXBElement) {
this.fooJAXBElement = fooJAXBElement;
}
#XmlElementRef(name="barJAXBElement")
public JAXBElement<String> getBarJAXBElement() {
return barJAXBElement;
}
public void setBarJAXBElement(JAXBElement<String> barJAXBElement) {
this.barJAXBElement = barJAXBElement;
}
}
ObjectFactory
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
import javax.xml.namespace.QName;
#XmlRegistry
public class ObjectFactory {
#XmlElementDecl(name="fooJAXBElement")
public JAXBElement<String> createFooJAXBElement(String string) {
return new JAXBElement<String>(new QName("fooJAXBElement"), String.class, string);
}
#XmlElementDecl(name="barJAXBElement")
public JAXBElement<String> createBarJAXBElement(String string) {
return new JAXBElement<String>(new QName("barJAXBElement"), String.class, string);
}
}
Demo
Below is a full example to demonstrate the concepts discussed above.
input.xml
This document contains 2 elements explicitly marked with xsi:nil="true" and 2 other mapped elements that are absent.
<?xml version="1.0" encoding="UTF-8"?>
<root>
<barString xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
<barJAXBElement xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
</root>
Demo
This demo code will read in the above XML and check whether the properties have been set as a result of the unmarshal.
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class, ObjectFactory.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum20076018/input.xml");
Root root = (Root) unmarshaller.unmarshal(xml);
System.out.println("Was fooString set? " + root.isSetFooString());
System.out.println("Was barString set? " + root.isSetBarString());
System.out.println("Was fooJAXBElement set? " + (root.getFooJAXBElement() != null));
System.out.println("Was barJAXBElement set? " + (root.getBarJAXBElement() != null));
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
Output
Below is the output from running the demo code. We see that all the is set checks are correct, but that the output only fully matches the input for the JAXBElement properties.
Was fooString set? false
Was barString set? true
Was fooJAXBElement set? false
Was barJAXBElement set? true
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<fooString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
<barString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
<barJAXBElement xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
</root>
I have some XML like this:
<root xml:base="http://www.example.com/foo">
<childElement someAttribute="bar/blort.html"/>
<childElement someAttribute="bar/baz/foo.html"/>
</root>
The schema for my XML defines someAttribute as being of type xs:anyURI
I want to use JAXB to unmarshall the XML into an object model a bit like this:
#XmlRootElement(name="root")
class Root {
#XmlElement(name="childElement")
private List<Child> _children;
}
class Child {
#XmlAttribute(name="someAttribute")
private URI _someAttribute;
}
I would like values of someAttribute to be resolved according to XML base, i.e. when I unmarshall the XML given above, I want the childrens' attributes to be resolved to java.net.URI instances with values http://www.example.com/foo/bar/blort.html and so on.
I was hoping a custom XmlAdapter would allow me to achieve the right result, but the XmlAdapter has no access to the surrounding context, in particular, the value of xml:base in effect at that point (note that this is not as simple as the most recent enclosing value of xml:base as xml:base can appear anywhere in the tree, and relative xml:bases must be resolved against their ancestors).
I'm using EclipseLink's MOXY implementation of JAXB, if it matters.
You can leverage an XMLStreamReader and an XmlAdapter to implement this use case:
UriAdapter
The UriAdapter is both an XmlAdapter for handling the URI property, and a StreamFilter that we will use to detect the xml:base attribute.
package forum9906642;
import java.net.URI;
import javax.xml.bind.annotation.adapters.*;
import javax.xml.stream.*;
public class UriAdapter extends XmlAdapter<String, URI> implements StreamFilter {
private String base = "";
public UriAdapter() {
}
public UriAdapter(String base) {
this.base = base;
}
public URI unmarshal(String string) throws Exception {
return new URI(base + '/' + string);
}
public String marshal(URI uri) throws Exception {
if("".equals(base)) {
return uri.toString();
} else {
URI baseURI = new URI(base);
return baseURI.relativize(uri).toString();
}
}
public boolean accept(XMLStreamReader reader) {
if(reader.isStartElement()) {
String newBase = reader.getAttributeValue("http://www.w3.org/XML/1998/namespace", "base");
if(null != newBase) {
base = newBase;
}
}
return true;
}
}
Demo
The code below demonstrates how to use all the pieces together:
package forum9906642;
import java.io.*;
import javax.xml.bind.*;
import javax.xml.stream.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
UriAdapter uriAdapter = new UriAdapter();
XMLInputFactory xif = XMLInputFactory.newFactory();
XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("src/forum9906642/input.xml"));
xsr = xif.createFilteredReader(xsr, uriAdapter);
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setAdapter(uriAdapter);
Root root = (Root) unmarshaller.unmarshal(xsr);
for(Child child : root.getChildren()) {
System.out.println(child.getSomeAttribute().toString());
}
Marshaller marshaller = jc.createMarshaller();
marshaller.setAdapter(uriAdapter);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
Child
package forum9906642;
import java.net.URI;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
#XmlAccessorType(XmlAccessType.FIELD)
class Child {
#XmlAttribute(name="someAttribute")
#XmlJavaTypeAdapter(UriAdapter.class)
private URI _someAttribute;
public URI getSomeAttribute() {
return _someAttribute;
}
public void setSomeAttribute(URI _someAttribute) {
this._someAttribute = _someAttribute;
}
}
Output
http://www.example.com/foo/bar/blort.html
http://www.example.com/foo/bar/baz/foo.html
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<childElement someAttribute="bar/blort.html"/>
<childElement someAttribute="bar/baz/foo.html"/>
</root>
I had a similar problem, but with nested xml:base (because of XInclude), so I ended up having to do this:
public class URIFixingUnmarshaller {
private final JAXBContext jaxb;
public URIFixingUnmarshaller(JAXBContext jaxb) {
this.jaxb = jaxb;
}
public <T> JAXBElement<T> unmarshal(SAXSource in, Class<T> as)
throws JAXBException {
CurrLocation curr = new CurrLocation(in.getXMLReader());
Unmarshaller u = jaxb.createUnmarshaller();
u.setListener(new URIUpdater(curr));
return u.unmarshal(new SAXSource(curr, in.getInputSource()), as);
}
private static class CurrLocation extends XMLFilterImpl {
private Locator curr;
public CurrLocation(XMLReader actual) {
setParent(actual);
}
#Override
public void setDocumentLocator(Locator to) {
super.setDocumentLocator(to);
this.curr = to;
}
String resolve(String uri) {
try {
URL base = new URL(curr.getSystemId());
URL absolute = new URL(base, uri);
return absolute.toString();
} catch (MalformedURLException probablyAlreadyAbsolute) {
return uri;
}
}
}
private static class URIUpdater extends Unmarshaller.Listener {
private final CurrLocation curr;
URIUpdater(CurrLocation curr) {
this.curr = curr;
}
#Override
public void afterUnmarshal(Object target, Object parent) {
if (target instanceof SomethingWithRelativeURI) {
SomethingWithRelativeURI casted = (SomethingWithRelativeURI) target;
casted.setPath(curr.resolve(casted.getPath()));
}
}
}
}
Is there any way to make JAXB not save fields which values are the default values specified in the #Element annotations, and then make set the value to it when loading elements from XML that are null or empties? An example:
class Example
{
#XmlElement(defaultValue="default1")
String prop1;
}
Example example = new Example();
example.setProp1("default1");
jaxbMarshaller.marshal(example, aFile);
Should generate:
<example/>
And when loading
Example example = (Example) jaxbUnMarshaller.unmarshal(aFile);
assertTrue(example.getProp1().equals("default1"));
I am trying to do this in order to generate a clean XML configuration file, and make it better readable and smaller size.
Regars and thanks in advance.
You could do something like the following by leveraging XmlAccessorType(XmlAccessType.FIELD) and putting logic in the get/set methods:
Example
package forum8885011;
import javax.xml.bind.annotation.*;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
class Example {
private static final String PROP1_DEFAULT = "default1";
private static final String PROP2_DEFAULT = "123";
#XmlElement(defaultValue=PROP1_DEFAULT)
String prop1;
#XmlElement(defaultValue=PROP2_DEFAULT)
Integer prop2;
public String getProp1() {
if(null == prop1) {
return PROP1_DEFAULT;
}
return prop1;
}
public void setProp1(String value) {
if(PROP1_DEFAULT.equals(value)) {
prop1 = null;
} else {
prop1 = value;
}
}
public int getProp2() {
if(null == prop2) {
return Integer.valueOf(PROP2_DEFAULT);
}
return prop2;
}
public void setProp2(int value) {
if(PROP2_DEFAULT.equals(String.valueOf(value))) {
prop2 = null;
} else {
prop2 = value;
}
}
}
Demo
package forum8885011;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Example.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Example example = new Example();
example.setProp1("default1");
example.setProp2(123);
System.out.println(example.getProp1());
System.out.println(example.getProp2());
marshaller.marshal(example, System.out);
example.setProp1("FOO");
example.setProp2(456);
System.out.println(example.getProp1());
System.out.println(example.getProp2());
marshaller.marshal(example, System.out);
}
}
Output
default1
123
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<example/>
FOO
456
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<example>
<prop1>FOO</prop1>
<prop2>456</prop2>
</example>
For More Information
http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html
For a programmatic solution, there's also good old Apache commons XmlSchema and you can check against the default value with XmlSchemaElement.getDefaultValue()
So with something like
XmlSchemaElement elem = schema.getElementByName(ELEMENT_QNAME);
String defval = elem.getDefaultValue();
you should be able to do what you need. Haven't tried it out in the end, because I needed a more direct solution, but I hope that helps.
I have an enum:
#XmlEnum
#XmlRootElement
public enum Product {
POKER("favourite-product-poker"),
SPORTSBOOK("favourite-product-casino"),
CASINO("favourite-product-sportsbook"),
SKILL_GAMES("favourite-product-skill-games");
private static final String COULD_NOT_FIND_PRODUCT = "Could not find product: ";
private String key;
private Product(final String key) {
this.key = key;
}
/**
* #return the key
*/
public String getKey() {
return key;
}
that I output in a REST service like so:
GenericEntity<List<Product>> genericEntity = new GenericEntity<List<Product>>(products) {
};
return Response.ok().entity(genericEntity).build();
and it outputs like this:
<products>
<product>POKER</product>
<product>SPORTSBOOK</product>
<product>CASINO</product>
<product>SKILL_GAMES</product>
</products>
I want it to output with both the enum name (i.e, POKER) and the key (i.e, "favourite-product-poker").
I have tried a number of different ways of doing this including using #XmlElement, #XmlEnumValue and #XmlJavaTypeAdapter, without getting both out at the same time.
Does anyone know how to achieve this, as you would for a normal JAXB annotated bean?
Thanks.
You could create a wrapper object for this, something like:
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
#XmlRootElement(name="product")
public class ProductWrapper {
private Product product;
#XmlValue
public Product getValue() {
return product;
}
public void setValue(Product value) {
this.product = value;
}
#XmlAttribute
public String getKey() {
return product.getKey();
}
}
This would correspond to the following XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<product key="favourite-product-poker">POKER</product>
You would need to pass instances of ProductWrapper to JAXB instead of Product.
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(ProductWrapper.class);
ProductWrapper pw = new ProductWrapper();
pw.setValue(Product.POKER);
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(pw, System.out);
}
}
You can use an adapter:
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
public class XmlEnumTest{
public static void main(String...str) throws Exception{
JAXBContext jc = JAXBContext.newInstance(ProductList.class);
StringWriter sw = new StringWriter();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(new ProductList(),sw);
System.out.println(sw.toString());
}
}
class ProductTypeAdaper extends XmlAdapter<ProductAdapter, Product> {
#Override
public Product unmarshal(ProductAdapter v) throws Exception {
return Product.valueOf(v.value);
}
#Override
public ProductAdapter marshal(Product v) throws Exception {
ProductAdapter result = new ProductAdapter();
result.key = v.getKey();
result.value = v.name();
return result;
}
}
#XmlType
class ProductAdapter{
#XmlAttribute
public String key;
#XmlValue
public String value;
}
#XmlJavaTypeAdapter(ProductTypeAdaper.class)
enum Product{
POKER("favourite-product-poker"),
SPORTSBOOK("favourite-product-casino"),
CASINO("favourite-product-sportsbook"),
SKILL_GAMES("favourite-product-skill-games");
private static final String COULD_NOT_FIND_PRODUCT = "Could not find product: ";
private String key;
private Product(final String key) {
this.key = key;
}
/**
* #return the key
*/
public String getKey() {
return key;
}
}
#XmlRootElement
#XmlSeeAlso({Product.class})
class ProductList{
#XmlElementWrapper(name="products")
#XmlElement(name="product")
private List<Product> list = new ArrayList<Product>(){{add(Product.POKER);add(Product.SPORTSBOOK);add(Product.CASINO);}};
}
You need to remove the #XmlEnum from your enum value, if you want it to be serialized into XML like a normal object. An enum (by definition) is represented in the XML by a single string symbol. This allows combining it with #XmlList, for example, to create an efficient, whitespace-separated list of items.