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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With